我正在编写一个程序,在嵌套 TreeMap 中存储有关足球队的数据。它看起来像这样:
TreeMap<[team name], TreeMap<[team wins], [opponents]>>
其中,[团队名称]和[对手]是字符串,[团队胜利]是整数。 我当前的目标是打印数据,按团队胜利降序排列。它必须看起来像:
Liverpool: //map key
wins: <wins> //nested map key
opponents: <opponents>
我的想法是订购嵌套映射entrySet(),然后在打印数据时迭代它,但我不能这样做,因为从我读到的内容来看,我需要TreeSet,而map.entry()只返回Set.I需要我的 map 是 TreeMap,因为当两支球队获胜时,我需要按字母顺序打印。如果我不清楚,打印按嵌套 TreeMap 键排序的 TreeMap 的好方法是什么?
最佳答案
TreeMap ( as the documentation states ) 自然地按您使用的键排序。所以,如果你想按获胜次数打印数据,那么你需要将获胜次数作为主键。
由于您希望辅助排序基于团队名称,因此您希望将其作为辅助键。
因此TreeMap<[wins], TreeMap<[team name], [opponents]>>
将是正确的方法。
此外,由于对手会暗示多个对手,因此您可能需要使其稍微复杂一些,并根据需要将其更改为以下内容:
TreeMap<[wins], TreeMap<[team name], ArrayList<[opponent]>>>
希望这能为您指明正确的方向。请记住,在您的情况下,外部 TreeMap 的自然排序将是降序,即 [wins]
因此,请确保您的可比对象的 compareTo
函数执行正确的工作。
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Random;
import java.util.TreeMap;
public class SO36799415 {
public static Random random = new Random();
public static void main(String[] args) {
TreeMap<Integer, TreeMap<String, ArrayList<String>>> map = new TreeMap(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return -Integer.compare(o1, o2);
}
});
int teams = random.nextInt(20) + 1;
for (int i = 0; i < teams; i++) {
addToMap(map);
}
for (Integer wins : map.keySet()) {
TreeMap<String, ArrayList<String>> tmp = map.get(wins);
for (String team : tmp.keySet()) {
System.out.println(team);
System.out.println("Wins: " + wins);
System.out.println(tmp.get(team));
System.out.println();
}
}
}
private static void addToMap(TreeMap<Integer, TreeMap<String, ArrayList<String>>> map) {
String name = randomName();
int wins = random.nextInt(10);
int opponents = random.nextInt(10) + 1;
Team team = new Team(name);
team.setWins(wins);
for (int i = 0; i < opponents; i++) {
team.addOpponent(randomName());
}
if (map.containsKey(wins)) {
map.get(wins).put(name, team.opponents);
} else {
TreeMap<String, ArrayList<String>> tmp = new TreeMap<>();
tmp.put(name, team.opponents);
map.put(wins, tmp);
}
}
private static String randomName() {
StringBuffer sb = new StringBuffer();
int len = random.nextInt(10) + 1;
for (int i = 0; i < len; i++) {
sb.append((char) ('a' + random.nextInt(26)));
}
return sb.toString();
}
private static class Team {
String name;
ArrayList<String> opponents;
int wins;
public Team(String name) {
this.name = name;
this.opponents = new ArrayList<>();
this.wins = 0;
}
public boolean addOpponent(String opponent) {
return this.opponents.add(opponent);
}
public void setWins(int wins) {
this.wins = wins;
}
}
}
关于Java按有序值打印TreeMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36799415/