[英]How to make Collectors.groupingBy() return a sorted LinkedHashMap?
For example, I have a List:例如,我有一个列表:
{Cat, Cat, Cat, Dog, Dog, Rat}
I want to return a sorted Map, in ascending or descending at my choice, where the keys are the animal names, and the values are their appearance times.我想返回一个排序的 Map,按我的选择升序或降序,其中键是动物名称,值是它们的出现时间。
For example例如
{
Rat: 1
Dog: 2
Cat: 3
}
By using通过使用
LinkedHashMap<String, Long> map =
list
.stream()
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
I can have a LinkedHashMap
, but it is not sorted.我可以有一个
LinkedHashMap
,但它没有排序。
I know that I can sort the Map afterward, but is there a way to do it in one stream?我知道我可以在之后对 Map 进行排序,但是有没有办法在一个 stream 中做到这一点?
Thanks!谢谢!
add sorted()
operator:添加
sorted()
运算符:
LinkedHashMap<String, Long> result = Arrays.stream(array)
.sorted()
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.