我正在制作一个记录足球比赛并显示联赛表的java项目。当两支球队之间的联赛中添加一场比赛时,我需要一种根据球队拥有的积分来存储球队在联赛中的位置的方法。
为此,我正在考虑使用 HashMap
例如,如果有三个团队
A队积8分, B队积5分 C队积4分
我希望这样订购 map
1:A, 2:乙, 3:C
我的问题是:
1) 你认为我应该在这个实例中使用 HashMap 还是 TreeMap?
2)我如何实现代码来按获得的积分对联赛进行排序?
最佳答案
列表
更适合您的用例。它为您提供开箱即用的索引和无忧排序。此外,它更适合有序显示值,例如在表格中等。
我将使Team
对象具有可比性,使用数组列表,然后我就完成了:
public class Team implements Comparable<Team> {
private int points;
private int goalDifference;
public Team(int points, int goalDifference) {
this.points = points;
this.goalDifference = goalDifference;
}
@Override
public int compareTo(Team other) {
int res = other.points - this.points;
return res != 0 ? res : (other.goalDifference - this.goalDifference);
}
//getters and setters
}
通过类似的 Team
类,您可以使用列表功能:
List<Team> teams = ...
Collections.sort(teams);
如果您不想使 Team
类具有可比性,则可以使用比较器(继续上面的代码段):
teams.sort((team1, team2) ->
(team2.getPoints() != team1.getPoints()) ?
(team2.getPoints() - team1.getPoints()) :
(team2.getGoalDifference() - team1.getGoalDifference())
);
请注意,在比较器或比较器中实现了降序逻辑。您可以选择使用反向比较器。
随着比较字段数量的增加,实现比较器的选项变得越来越可取。我个人更喜欢这样,因为它更具可读性。
关于java - 按值对 HashMap 或 TreeMap 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47957384/