什么是反转嵌套 java 地图顺序的正确方法
What is a proper way to reverse the order of nested java Maps
我正在尝试反转嵌套地图的顺序。
由于Map中没有内置函数来颠倒顺序,我没时间了。我尝试了几种可用的方法来反转开发人员发布的顺序,但没有任何效果,而且我也没有看到任何错误。我不知道代码有什么问题可能是因为我没有那么多地使用 Map 并且我对 java.
比较陌生
这是地图的结构
Map<String, HashMap<String, Object>> playersDataMap = new HashMap<> ();
这些是我从网站上复制的几种方法,但其中 none 有效。它总是 returns 我以相同的顺序。
public static <K extends Comparable, V> Map<K,V> sortByKeys(Map<K,V> map)
{
Map<K, V> treeMap = new TreeMap<>(new Comparator<K>() {
@Override
public int compare(K a, K b) {
return b.compareTo(a);
}
});
treeMap.putAll(map);
return treeMap;
}
public static <K, V> Map<K,V> sortByTreeMap(Map<K,V> unsortedMap)
{
// construct a TreeMap from given Map and return a reverse order
// view of the mappings contained in this map
return new TreeMap<>(unsortedMap).descendingMap();
}
我也尝试过将 HashMap 更改为 LinkedHashMap 但没有成功,结果相同。
请让我知道代码有什么问题。我真的没时间了,否则我会在发布甚至实施之前阅读 Maps 的文档。对你的帮助表示感谢。谢谢
这是我要实现的示例
Map<String, HashMap<String, Object>> playersDataMap = new LinkedHashMap<> ();
for (int i = 1; i < 40; i++)
{
HashMap<String, Object> playerMap = new HashMap<> ();
playerMap.put ("name", "abc"+i);
playerMap.put ("pointsScored", i * 10);
playersDataMap.put ("x"+i, playerMap);
}
Map<String, HashMap<String, Object>> inversedPlayerDataMap = new LinkedHashMap<>();
inversedPlayerDataMap = new TreeMap<>(Comparator.reverseOrder());
inversedPlayerDataMap.putAll(playersDataMap);
for (Map.Entry<String, HashMap<String, Object>> player : inversedPlayerDataMap.entrySet ())
{
System.out.printf ("Debug: player key: %s playerValueScore: %s \n", player.getKey (), player.getValue ().get("pointsScored"));
}
结果:"Debug: player key: x9 pointsScored: 90" "Debug: player key: x390 pointsScored: 390" "Debug: player key: x30 pointsScored: 30" ...
预期输出:"Debug: player key: x390 pointsScored: 390" "Debug: player key: x380 pointsScored: 380" ...
[原回答]
您使用 Map
的方法可能会有问题。您应该创建一个新类型并使用新类型的 List
。
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class MyType {
String playerKey;
Map<String, Object> map = new HashMap<String, Object>();
public MyType(String id, Map<String, Object> map) {
this.playerKey = id;
this.map = map;
}
public String getPlayerKey() {
return playerKey;
}
@Override
public String toString() {
return "playerKey=" + playerKey + ", pointsScored=" + map.get("pointsScored");
}
}
public class Main {
public static void main(String[] args) {
List<MyType> playersData = new ArrayList<MyType>();
playersData.add(new MyType("x1", Map.of("name", "john", "pointsScored", 50)));
playersData.add(new MyType("x11", Map.of("name", "harry", "pointsScored", 55)));
playersData.add(new MyType("x2", Map.of("name", "tina", "pointsScored", 60)));
playersData.add(new MyType("y1", Map.of("name", "richard", "pointsScored", 60)));
playersData.add(new MyType("y12", Map.of("name", "kim", "pointsScored", 45)));
playersData.add(new MyType("y3", Map.of("name", "karen", "pointsScored", 65)));
System.out.println("Orinally:");
playersData.stream().forEach(System.out::println);
playersData.sort(new Comparator<MyType>() {
@Override
public int compare(MyType t1, MyType t2) {
String s1 = t1.getPlayerKey();
String s2 = t2.getPlayerKey();
int compVal;
int n1 = 0, n2 = 0;
String sn1 = "", sn2 = "";
// Pattern to find a sequence of digits
Pattern pattern = Pattern.compile("\d+");
Matcher matcher;
matcher = pattern.matcher(s1);
if (matcher.find()) {
// Number from first string
sn1 = matcher.group();
n1 = Integer.valueOf(sn1);
}
matcher = pattern.matcher(s2);
if (matcher.find()) {
// Number from first string
sn2 = matcher.group();
n2 = Integer.valueOf(sn2);
}
// Compare the string part
compVal = s2.substring(0, s2.indexOf(sn2)).compareTo(s1.substring(0, s1.indexOf(sn1)));
// If string parts are same, compare the number parts
if (compVal == 0 && n1 != 0 && n2 != 0) {
compVal = Integer.compare(n2, n1);
}
return compVal;
}
});
System.out.println("\nSorted in reversed order of playerKey:");
playersData.stream().forEach(System.out::println);
}
}
[更新]
您可以通过以下方式使用Map
:
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* Comparator to compare alphanumeric words in the form of LETTERS+DIGITs e.g.
* A1, ABC123 etc.
*
*/
class MyComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
int compVal;
int n1 = 0, n2 = 0;
String sn1 = "", sn2 = "";
// Pattern to find a sequence of digits
Pattern pattern = Pattern.compile("\d+");
Matcher matcher;
matcher = pattern.matcher(s1);
if (matcher.find()) {
// Number from first string
sn1 = matcher.group();
n1 = Integer.valueOf(sn1);
}
matcher = pattern.matcher(s2);
if (matcher.find()) {
// Number from first string
sn2 = matcher.group();
n2 = Integer.valueOf(sn2);
}
// Compare the string part
compVal = s2.substring(0, s2.indexOf(sn2)).compareTo(s1.substring(0, s1.indexOf(sn1)));
// If string parts are same, compare the number parts
if (compVal == 0 && n1 != 0 && n2 != 0) {
compVal = Integer.compare(n2, n1);
}
return compVal;
}
}
public class Main {
public static void main(String[] args) {
Map<String, HashMap<String, Object>> playersDataMap = new HashMap<>();
for (int i = 1; i <= 10; i++) {
HashMap<String, Object> playerMap = new HashMap<>();
playerMap.put("name", "abc" + i);
playerMap.put("pointsScored", i * 10);
playersDataMap.put("x" + i, playerMap);
}
Map<String, HashMap<String, Object>> inversedPlayerDataMap = new TreeMap<>(new MyComparator());
inversedPlayerDataMap.putAll(playersDataMap);
for (Map.Entry<String, HashMap<String, Object>> entry : inversedPlayerDataMap.entrySet()) {
System.out
.println("playerKey=" + entry.getKey() + ", pointsScored=" + entry.getValue().get("pointsScored"));
}
}
}
输出:
playerKey=x10, pointsScored=100
playerKey=x9, pointsScored=90
playerKey=x8, pointsScored=80
playerKey=x7, pointsScored=70
playerKey=x6, pointsScored=60
playerKey=x5, pointsScored=50
playerKey=x4, pointsScored=40
playerKey=x3, pointsScored=30
playerKey=x2, pointsScored=20
playerKey=x1, pointsScored=10
如果您只想反转当前地图,那么这就可以了。
这是测试地图
for (int i = 10; i < 300; i += 10) {
playerMap = new HashMap<String, Object>();
playerMap.put("name", "person" + (i / 10));
playerMap.put("pointsScored", i);
playersDataMap.put("x" + i, playerMap);
}
这是比较器。请注意,这取决于 x
与封闭映射中的键相同。
Comparator<String> comp = Comparator
.comparing(String::length)
.thenComparing(String::compareTo)
.reversed();
以及排序
inversedPlayerDataMap = new TreeMap<>(comp);
inversedPlayerDataMap.putAll(playersDataMap);
for (Map.Entry<String, HashMap<String, Object>> player : inversedPlayerDataMap
.entrySet()) {
System.out.printf(
"Debug: player key: %s playerValueScore: %s \n",
player.getKey(),
player.getValue().get("pointsScored"));
}
}
版画
...
...
...
Debug: player key: x130 playerValueScore: 130
Debug: player key: x120 playerValueScore: 120
Debug: player key: x110 playerValueScore: 110
Debug: player key: x100 playerValueScore: 100
Debug: player key: x90 playerValueScore: 90
Debug: player key: x80 playerValueScore: 80
...
...
...
不过不确定您为什么要使用地图中的地图。 outerMap 的关键是否重要(也许像团队指示符?)
以上两个答案都有效,但在一定程度上有效。他们没有在混合字符串上工作。
所以我所做的是将 HashMap 替换为 linkedHashMap。然后我将该 Map 的 keySet 添加到新创建的字符串列表中,并使用 Collections.reverse 反转它,然后遍历该列表并将保留顺序添加到新 Map 中。
这是我的反转函数的代码。
重要,我作为 playersDataMap 传递的参数是 linkedHashMap。关于LinkedHashMap的进一步解释请看下面linkhttps://beginnersbook.com/2013/12/linkedhashmap-in-java/。谢谢!
public static Map<String, HashMap<String, Object>> invertMapUsingList (Map<String, HashMap<String, Object>> playersDataMap)
{
Map<String, HashMap<String, Object>> inversedPlayerDataMap = new LinkedHashMap<> ();
List<String> reverseOrderedKeys = new ArrayList<String>(playersDataMap.keySet());
Collections.reverse(reverseOrderedKeys);
for (String key : reverseOrderedKeys)
{
inversedPlayerDataMap.put (key, playersDataMap.get(key));
}
return inversedPlayerDataMap;
}
我正在尝试反转嵌套地图的顺序。
由于Map中没有内置函数来颠倒顺序,我没时间了。我尝试了几种可用的方法来反转开发人员发布的顺序,但没有任何效果,而且我也没有看到任何错误。我不知道代码有什么问题可能是因为我没有那么多地使用 Map 并且我对 java.
比较陌生这是地图的结构
Map<String, HashMap<String, Object>> playersDataMap = new HashMap<> ();
这些是我从网站上复制的几种方法,但其中 none 有效。它总是 returns 我以相同的顺序。
public static <K extends Comparable, V> Map<K,V> sortByKeys(Map<K,V> map)
{
Map<K, V> treeMap = new TreeMap<>(new Comparator<K>() {
@Override
public int compare(K a, K b) {
return b.compareTo(a);
}
});
treeMap.putAll(map);
return treeMap;
}
public static <K, V> Map<K,V> sortByTreeMap(Map<K,V> unsortedMap)
{
// construct a TreeMap from given Map and return a reverse order
// view of the mappings contained in this map
return new TreeMap<>(unsortedMap).descendingMap();
}
我也尝试过将 HashMap 更改为 LinkedHashMap 但没有成功,结果相同。
请让我知道代码有什么问题。我真的没时间了,否则我会在发布甚至实施之前阅读 Maps 的文档。对你的帮助表示感谢。谢谢
这是我要实现的示例
Map<String, HashMap<String, Object>> playersDataMap = new LinkedHashMap<> ();
for (int i = 1; i < 40; i++)
{
HashMap<String, Object> playerMap = new HashMap<> ();
playerMap.put ("name", "abc"+i);
playerMap.put ("pointsScored", i * 10);
playersDataMap.put ("x"+i, playerMap);
}
Map<String, HashMap<String, Object>> inversedPlayerDataMap = new LinkedHashMap<>();
inversedPlayerDataMap = new TreeMap<>(Comparator.reverseOrder());
inversedPlayerDataMap.putAll(playersDataMap);
for (Map.Entry<String, HashMap<String, Object>> player : inversedPlayerDataMap.entrySet ())
{
System.out.printf ("Debug: player key: %s playerValueScore: %s \n", player.getKey (), player.getValue ().get("pointsScored"));
}
结果:"Debug: player key: x9 pointsScored: 90" "Debug: player key: x390 pointsScored: 390" "Debug: player key: x30 pointsScored: 30" ...
预期输出:"Debug: player key: x390 pointsScored: 390" "Debug: player key: x380 pointsScored: 380" ...
[原回答]
您使用 Map
的方法可能会有问题。您应该创建一个新类型并使用新类型的 List
。
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class MyType {
String playerKey;
Map<String, Object> map = new HashMap<String, Object>();
public MyType(String id, Map<String, Object> map) {
this.playerKey = id;
this.map = map;
}
public String getPlayerKey() {
return playerKey;
}
@Override
public String toString() {
return "playerKey=" + playerKey + ", pointsScored=" + map.get("pointsScored");
}
}
public class Main {
public static void main(String[] args) {
List<MyType> playersData = new ArrayList<MyType>();
playersData.add(new MyType("x1", Map.of("name", "john", "pointsScored", 50)));
playersData.add(new MyType("x11", Map.of("name", "harry", "pointsScored", 55)));
playersData.add(new MyType("x2", Map.of("name", "tina", "pointsScored", 60)));
playersData.add(new MyType("y1", Map.of("name", "richard", "pointsScored", 60)));
playersData.add(new MyType("y12", Map.of("name", "kim", "pointsScored", 45)));
playersData.add(new MyType("y3", Map.of("name", "karen", "pointsScored", 65)));
System.out.println("Orinally:");
playersData.stream().forEach(System.out::println);
playersData.sort(new Comparator<MyType>() {
@Override
public int compare(MyType t1, MyType t2) {
String s1 = t1.getPlayerKey();
String s2 = t2.getPlayerKey();
int compVal;
int n1 = 0, n2 = 0;
String sn1 = "", sn2 = "";
// Pattern to find a sequence of digits
Pattern pattern = Pattern.compile("\d+");
Matcher matcher;
matcher = pattern.matcher(s1);
if (matcher.find()) {
// Number from first string
sn1 = matcher.group();
n1 = Integer.valueOf(sn1);
}
matcher = pattern.matcher(s2);
if (matcher.find()) {
// Number from first string
sn2 = matcher.group();
n2 = Integer.valueOf(sn2);
}
// Compare the string part
compVal = s2.substring(0, s2.indexOf(sn2)).compareTo(s1.substring(0, s1.indexOf(sn1)));
// If string parts are same, compare the number parts
if (compVal == 0 && n1 != 0 && n2 != 0) {
compVal = Integer.compare(n2, n1);
}
return compVal;
}
});
System.out.println("\nSorted in reversed order of playerKey:");
playersData.stream().forEach(System.out::println);
}
}
[更新]
您可以通过以下方式使用Map
:
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* Comparator to compare alphanumeric words in the form of LETTERS+DIGITs e.g.
* A1, ABC123 etc.
*
*/
class MyComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
int compVal;
int n1 = 0, n2 = 0;
String sn1 = "", sn2 = "";
// Pattern to find a sequence of digits
Pattern pattern = Pattern.compile("\d+");
Matcher matcher;
matcher = pattern.matcher(s1);
if (matcher.find()) {
// Number from first string
sn1 = matcher.group();
n1 = Integer.valueOf(sn1);
}
matcher = pattern.matcher(s2);
if (matcher.find()) {
// Number from first string
sn2 = matcher.group();
n2 = Integer.valueOf(sn2);
}
// Compare the string part
compVal = s2.substring(0, s2.indexOf(sn2)).compareTo(s1.substring(0, s1.indexOf(sn1)));
// If string parts are same, compare the number parts
if (compVal == 0 && n1 != 0 && n2 != 0) {
compVal = Integer.compare(n2, n1);
}
return compVal;
}
}
public class Main {
public static void main(String[] args) {
Map<String, HashMap<String, Object>> playersDataMap = new HashMap<>();
for (int i = 1; i <= 10; i++) {
HashMap<String, Object> playerMap = new HashMap<>();
playerMap.put("name", "abc" + i);
playerMap.put("pointsScored", i * 10);
playersDataMap.put("x" + i, playerMap);
}
Map<String, HashMap<String, Object>> inversedPlayerDataMap = new TreeMap<>(new MyComparator());
inversedPlayerDataMap.putAll(playersDataMap);
for (Map.Entry<String, HashMap<String, Object>> entry : inversedPlayerDataMap.entrySet()) {
System.out
.println("playerKey=" + entry.getKey() + ", pointsScored=" + entry.getValue().get("pointsScored"));
}
}
}
输出:
playerKey=x10, pointsScored=100
playerKey=x9, pointsScored=90
playerKey=x8, pointsScored=80
playerKey=x7, pointsScored=70
playerKey=x6, pointsScored=60
playerKey=x5, pointsScored=50
playerKey=x4, pointsScored=40
playerKey=x3, pointsScored=30
playerKey=x2, pointsScored=20
playerKey=x1, pointsScored=10
如果您只想反转当前地图,那么这就可以了。
这是测试地图
for (int i = 10; i < 300; i += 10) {
playerMap = new HashMap<String, Object>();
playerMap.put("name", "person" + (i / 10));
playerMap.put("pointsScored", i);
playersDataMap.put("x" + i, playerMap);
}
这是比较器。请注意,这取决于 x
与封闭映射中的键相同。
Comparator<String> comp = Comparator
.comparing(String::length)
.thenComparing(String::compareTo)
.reversed();
以及排序
inversedPlayerDataMap = new TreeMap<>(comp);
inversedPlayerDataMap.putAll(playersDataMap);
for (Map.Entry<String, HashMap<String, Object>> player : inversedPlayerDataMap
.entrySet()) {
System.out.printf(
"Debug: player key: %s playerValueScore: %s \n",
player.getKey(),
player.getValue().get("pointsScored"));
}
}
版画
...
...
...
Debug: player key: x130 playerValueScore: 130
Debug: player key: x120 playerValueScore: 120
Debug: player key: x110 playerValueScore: 110
Debug: player key: x100 playerValueScore: 100
Debug: player key: x90 playerValueScore: 90
Debug: player key: x80 playerValueScore: 80
...
...
...
不过不确定您为什么要使用地图中的地图。 outerMap 的关键是否重要(也许像团队指示符?)
以上两个答案都有效,但在一定程度上有效。他们没有在混合字符串上工作。
所以我所做的是将 HashMap 替换为 linkedHashMap。然后我将该 Map 的 keySet 添加到新创建的字符串列表中,并使用 Collections.reverse 反转它,然后遍历该列表并将保留顺序添加到新 Map 中。
这是我的反转函数的代码。
重要,我作为 playersDataMap 传递的参数是 linkedHashMap。关于LinkedHashMap的进一步解释请看下面linkhttps://beginnersbook.com/2013/12/linkedhashmap-in-java/。谢谢!
public static Map<String, HashMap<String, Object>> invertMapUsingList (Map<String, HashMap<String, Object>> playersDataMap)
{
Map<String, HashMap<String, Object>> inversedPlayerDataMap = new LinkedHashMap<> ();
List<String> reverseOrderedKeys = new ArrayList<String>(playersDataMap.keySet());
Collections.reverse(reverseOrderedKeys);
for (String key : reverseOrderedKeys)
{
inversedPlayerDataMap.put (key, playersDataMap.get(key));
}
return inversedPlayerDataMap;
}