如何使 Collectors.groupingBy() return 成为排序的 LinkedHashMap?

How to make Collectors.groupingBy() return a sorted LinkedHashMap?

比如我有一个列表:

{Cat, Cat, Cat, Dog, Dog, Rat}

我想要return一个排序的Map,按我的选择升序或降序,其中键是动物名称,值是它们出现的时间。

例如

{
    Rat: 1
    Dog: 2
    Cat: 3
}

通过使用

LinkedHashMap<String, Long> map = 
    list
    .stream()                              
    .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));

我可以有一个LinkedHashMap,但它没有排序

我知道之后我可以对 Map 进行排序,但是有没有办法在一个流中进行排序?

谢谢!

添加sorted()运算符:

LinkedHashMap<String, Long> result = Arrays.stream(array)
                .sorted()
                .collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));