所以我现在正在尝试为一个学校项目做的是使用外部文件制作一个小型高分系统,并使用 TreeMap 将人名映射到他们的分数。然而,仅仅基于我迭代它的方式的性质,数字是碎片化的,我想让它们按降序排列,但我不确定如何。任何帮助,将不胜感激!谢谢!
File dir = new File(System.getProperty("user.dir") + "/saves");
try {
TreeMap<String, Character> scores2 = new TreeMap<>();
for (File file : dir.listFiles()) {
InputStream in = new FileInputStream(file);
String name = file.getName().replace(".dat", "");
int content;
while((content = in.read())!=-1) {
char num = (char)content;
scores2.put(name, num);
}
}
Text top5 = new Text();
for (int i = 0; i < dir.list().length; i++) {
Map.Entry<String, Character> currentEntry = scores2.pollFirstEntry();
String name = currentEntry.getKey();
Character score = currentEntry.getValue();
top5.setText(top5.getText() + name + ": " + score + "\n");
}
newPane.setAlignment(Pos.CENTER);
newPane.add(top5, 1, 1);
Button exit = new Button("Arrière");
exit.setOnMouseClicked(mEv -> scene.setRoot(pane));
newPane.add(exit, 1, 3);
scene.setRoot(newPane);
}catch(NullPointerException | IOException e) {
e.printStackTrace();
Text txt = new Text("Il n'y a pas de scores pour montrer.");
Button returnButto = new Button("Retourner?");
GridPane errPane = new GridPane();
errPane.add(txt, 1, 1);
errPane.add(returnButto, 1, 2);
errPane.setAlignment(Pos.CENTER);
scene.setRoot(errPane);
returnButto.setOnMouseClicked(mcEv -> scene.setRoot(pane));
}
最佳答案
如 java docs 中所述,树形图:
is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.
因此,您需要创建自己的比较器,按降序对元素进行排序并将其传递给相应的 TreeMap 构造函数。
关于java - 如何使用降序键对 TreeMap 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36855778/