我想把一个嵌套的Map的顺序反过来。
由于Map中没有内置的反转顺序的功能,而我又没有时间。我尝试了开发人员发布的几种可用的反转顺序的方法,但都没有成功,而且我也没有看到任何错误。我不知道代码出了什么问题,可能是因为我没怎么用过Map,而且我对java比较陌生。
下面是地图的结构Map<String, HashMap<String, Object>> playersDataMap = new HashMap<> ();
而这几个方法是我从一个网站上抄来的,但都没有用。它总是以相同的顺序返回给我。
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"));
}
结果:"调试:球员键:x9分得分 "Debug: player key: x9 pointsScored. 90" "Debug: player key: x390 pointsScored: 90" "Debug: player key: x390 pointsScored, 390" "Debug: player key: x30 pointsScored, 390" "Debug: player key: 390" "Debug: player key: x30 pointsScored: 30" ...
预期的输出:"Debug: player key: x390 pointsScored: 390" "Debug: player key: x30 pointsScored: 30" ..: "Debug: player key: x390 pointsScored." "Debug: player key: x390 pointsScored: 390" "Debug: player key: x380 pointsScored: 380" ...
如果你想做的只是把当前的地图反过来,那么这个就可以了。
下面是测试地图
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
...
...
...
虽然不确定你为什么要用Map of Maps,但。 外层Map的关键有什么重要意义吗(比如说可能是一个团队代号?
你使用的方法是 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
以上两个答案都有效,但在某种程度上。它们在混合字符串上不起作用。
所以我所做的是将HashMap替换为linkedHashMap。然后我将该Map的keySet添加到新创建的字符串列表中,并使用Collections.reverse进行反转,然后在该列表中进行迭代,并将保留的顺序添加到一个新的Map中。
下面是我的反转函数的代码。
重要提示我传递给球员数据Map的参数是一个LinkedHashMap。关于LinkedHashMap的更多解释,请访问以下链接。https:/beginnersbook.com201312linkedhashmap-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;
}