我可以将单词列表收集到一个袋子中
(也称为多集合):(参见链接)Map<String, Long> bag =
Arrays.asList("one o'clock two o'clock three o'clock rock".split(" "))
.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
然而,袋子中的条目没有任何特定顺序的保证。例如,
{rock=1, o'clock=3, one=1, three=1, two=1}
我可以将它们放入一个列表中,然后使用我的值比较器实现对它们进行排序:
ArrayList<Entry<String, Long>> list = new ArrayList<>(bag.entrySet());
Comparator<Entry<String, Long>> valueComparator = new Comparator<Entry<String, Long>>() {
@Override
public int compare(Entry<String, Long> e1, Entry<String, Long> e2) {
return e2.getValue().compareTo(e1.getValue());
}
};
Collections.sort(list, valueComparator);
这将得到所需的结果:
[o'clock=3, rock=1, one=1, three=1, two=1]
有没有更优雅的方法来处理这个问题?我相信很多人都解决过这个问题。Java Streams API 中是否内置了我可以使用的东西?