作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下列表:
Map<String, Integer> map = new HashMap<String, Integer>();
Map<String, Map<Integer, Integer>> map2 = new HashMap<String, Map<Integer, Integer>>();
使用以下代码在我的 map 列表中进行一些计算后
map.entrySet().stream().sorted(Map.Entry.<String, Integer>comparingByValue()
.reversed()).limit(1000).forEach(System.out::println);
它返回一个根据整数和名称排序的列表:
team1=1511
team4=1106
team2=805
team3=792
这意味着 team1 获得第一名,时间为 1211,而 team4 获得第二名,时间为 1106,依此类推。
现在,在我的map2中,我希望能够根据司机的时间拥有相同的列表,但它应该像这样排序:
team1=1511
team4=1106
team1=1010
team2=905
team2=892
team3=750
team3=740
team4=600
这意味着 team1 以时间 1511 获得第一名,然后 team4 以时间 1106 获得第一名,然后 team1 以时间 1010 获得第一名,依此类推。
(基本上,您有一个团队,每个团队至少有 2 名车手,在进行一些计算后,您希望能够看到谁赢得了比赛)
对于map2,我使用以下内容进行排序和返回:
map2.entrySet().stream().sorted(Map.Entry.<String, Map<Integer, Integer>>comparingByKey()
.reversed()).limit(1000).forEach(System.out::println);
但这不会返回正确的结果。
我想知道是否可以使用 hashmap 或什至使用 ArrayList 来做到这一点?
最佳答案
另一种方法......为什么不一个单独的类?
public class Standing implements Comparable<Standing> {
private String team;
private Integer time;
public Standing(String team, Integer time) {
this.team = team;
this.time = time;
}
public String getTeam() {
return this.team;
}
public Integer getTime() {
return this.time;
}
@Override
public String toString() {
return this.team + "=" + this.time;
}
public int compareTo(Standing standing) {
return (this.time).compareTo(standing.getTime());
}
}
这里我会使用:
Map<String, ArrayList<Integer>> map2 = new HashMap<String, ArrayList<Integer>();
这样:
TreeSet<Standing> standingSet = new TreeSet<Standing>();
for (String team : map2.keySet()) {
standingSet.add(new Standing(team, map2.get(team).get(0)));
standingSet.add(new Standing(team, map2.get(team).get(1)));
}
for (Standing standing : standingSet) {
System.out.println(standing);
}
关于java - 如何对列表 HashMap 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41663070/
我是一名优秀的程序员,十分优秀!