TreeMap的(as the documentation states)自然按您使用的鍵排序。所以,如果你想通過勝利數量打印數據,那麼你需要將勝利數量作爲主鍵。
既然你希望你的二級排序是基於團隊名稱,那麼你會希望這是你的次要關鍵。因此TreeMap<[wins], TreeMap<[team name], [opponents]>>
將是正確的方法。
此外,由於對手將意味着超過一個對手,你可能要使它稍微複雜一點,並將其更改爲以下如果需要的話:
TreeMap<[wins], TreeMap<[team name], ArrayList<[opponent]>>>
希望這點你在正確的方向。請記住,您的案例中的自然順序將是外部TreeMap的降級順序,即對於[wins]
,請確保您的Comparable的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;
}
}
}
你真的有問題嗎? –
爲了獲得體面的幫助,請創建併發佈一個體面的[最小,完整和可驗證示例](https://stackoverflow.com/help/mcve)。請閱讀此重要鏈接以瞭解詳細信息。 – dsh
在高層次上,您將使用List來存儲對手,然後在打印之前調用Collections.sort()對列表進行排序。 – dsh