如何在Java流中按值降序对LinkedHashMap进行排序?
可以按升序对它进行排序:
myMap.entrySet().stream()    .sorted(Map.Entry.comparingByValue())
    .collect(Collectors.toMap(Entry::getKey, Entry::getValue));
如何按降序排列?
回答:
要以相反顺序排序,请将Comparator.reverseOrder()作为参数传递给comparingByValue。
要获取a
LinkedHashMap,您必须明确要求使用4参数toMap()。如果您未指定所需的地图类型,则将获得默认值,而默认值是HashMap。由于HashMap不保留元素的顺序,因此绝对不会为您服务。
myMap.entrySet().stream()        .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
        .collect(Collectors.toMap(
                Map.Entry::getKey, 
                Map.Entry::getValue, 
                (x,y)-> {throw new AssertionError();},
                LinkedHashMap::new
        ));
使用静态导入,它将变得更加令人愉快:
myMap.entrySet().stream()        .sorted(comparingByValue(reverseOrder()))
        .collect(toMap(
                Map.Entry::getKey, 
                Map.Entry::getValue, 
                (x,y)-> {throw new AssertionError();},
                LinkedHashMap::new
        ));
以上是 如何在Java流中按值降序对LinkedHashMap进行排序? 的全部内容, 来源链接: utcz.com/qa/431499.html
