java - 如何在Java流中按值按降序对LinkedHashMap进行排序?

How to sort a LinkedHashMap by value in decreasing order in java stream?(java - 如何在Java流中按值按降序对LinkedHashMap进行排序?)

本文介绍了java - 如何在Java流中按值按降序对LinkedHashMap进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要按升序排序,我可以使用:

To sort it int ascending order I can use:

myMap.entrySet().stream()
    .sorted(Map.Entry.comparingByValue())
    .collect(Collectors.toMap(Entry::getKey, Entry::getValue));

如何按降序进行?

推荐答案

要逆序排序,请将 Comparator.reverseOrder() 作为参数传递给 comparingByValue.

To sort in reverse order, pass Comparator.reverseOrder() as parameter to comparingByValue.

要获得 LinkedHashMap,您必须专门请求一个带有 4 参数的 toMap().如果你没有指定你想要什么样的映射,你会得到默认的,当前恰好是一个HashMap.由于 HashMap 不保留元素的顺序,它肯定不适合你.

To get a LinkedHashMap, you must specifically request one with the 4-argument toMap(). If you don't specify what kind of a map you want, you will get whatever the default is, which currently happens to be a HashMap. Since HashMap doesn't preserve the order of elements, it will definitely not do for you.

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
        ));

使用静态导入,它变得更令人愉快:

With static imports, it becomes a bit more pleasant:

myMap.entrySet().stream()
        .sorted(comparingByValue(reverseOrder()))
        .collect(toMap(
                Map.Entry::getKey, 
                Map.Entry::getValue, 
                (x,y)-> {throw new AssertionError();},
                LinkedHashMap::new
        ));

这篇关于java - 如何在Java流中按值按降序对LinkedHashMap进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:java - 如何在Java流中按值按降序对LinkedHashMap进行排序?

基础教程推荐