如何先按值对映射条目进行排序,然后按键排序,然后将排序后的键放入列表中? [英] How to sort Map entries by values first, then by key and put the ordered keys in a List?
本文介绍了如何先按值对映射条目进行排序,然后按键排序,然后将排序后的键放入列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 HashMap :
private Map<String,Integer> matchesWonByTeam= new HashMap<String,Integer>();
- 我需要按比赛获胜次数(值)对这些球队进行排序,并返回带有球队名称的ArrayList.
- 如果其中任何一支球队赢得的比赛数量相同,则需要按字母顺序排列.
使用集合和比较器"来做到这一点的最短,最简单的方法是什么?
What is the shortest and simplest way to do that using Collections and Comparators?
推荐答案
您可以使用函数式编程来做到这一点:
You could do it that way using functional programming :
final Map<String, Integer> map = new HashMap<>();
map.put("test", 1);
map.put("test1", 3);
map.put("test3", 4);
map.put("test2", 75);
map.put("a", 75);
map.put("test100", 100);
final List<String> test = map
.entrySet()
.stream()
.sorted((Entry<String, Integer> o1, Entry<String, Integer> o2) -> {
return o1.getValue().equals(o2.getValue()) ?
o1.getKey().compareTo(o2.getKey())
: o1.getValue().compareTo(o2.getValue());
})
.map(e -> e.getKey())
.collect(Collectors.toList());
for(String s : test)
System.out.println(s);
此示例将输出
test test1 test3 a test2 test100
test test1 test3 a test2 test100
这篇关于如何先按值对映射条目进行排序,然后按键排序,然后将排序后的键放入列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文