gpt4 book ai didi

java - 如何对列表 HashMap 进行排序?

转载 作者:行者123 更新时间:2023-12-02 05:29:34 25 4
gpt4 key购买 nike

我有以下列表:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com