【发布时间】:2018-06-11 19:44:04
【问题描述】:
如何按玩家id或玩家姓名对地图(复杂度为O(log(n)))进行排序??
private static final Map<Integer,Player> PLAYERS= new TreeMap<>();
static {
PLAYERS.put(1, new Player(1, "messi"));
PLAYERS.put(2, new Player(7, "ronaldo"));
PLAYERS.put(3, new Player(3, "neymar"));
PLAYERS.put(4, new Player(4, "iniesta"));
PLAYERS.put(5, new Player(5, "ronaldo"));
PLAYERS.put(6, new Player(2, "pique"));
PLAYERS.put(7, new Player(6, "suarez"));
}
我做了这个比较器,例如:
public static Comparator<Player> PlayerNameComparator = new
Comparator<Player>() {
public int compare(Player p1, Player p2) {
String playerName1 = p1.getName().toUpperCase();
String playerName2 = p2.getName().toUpperCase();
return playerName1.compareTo(playerName2);
}
};
但我不知道如何解决这个问题:
public static Collection getAllByName() {
Map sortedPlayersByName = new TreeMap(PLAYERS);
Collections.sort(sortedPlayersByName, Player.PlayerNameComparator);
return sortedPlayersByName.values();
}
【问题讨论】:
-
阅读this
-
您无法对地图进行排序,期间。
-
那么我怎样才能按名称对集合进行排序并且仍然具有 O(log(n)) 的复杂性?
标签: java sorting dictionary complexity-theory