JDK8 新特性-Map对key和value分别排序实现

在Java 8 中使用Stream 例子对一个 Map 进行按照keys或者values排序。

1. 快速入门

在java 8中按照此步骤对map进行排序.

  1. 将 Map 转换为 Stream
  2. 对其进行排序
  3. Collect and return a new LinkedHashMap (保持顺序)
Map result = map.entrySet().stream()
    .sorted(Map.Entry.comparingByKey())
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
    (oldValue, newValue) -> oldValue, LinkedHashMap::new));

默认情况下, Collectors.toMap 将返回一个 HashMap。

在这里通过使用toMap方法的另一个变体来处理重复问题,它允许我们指定一个合并方法((oldValue, newValue) -> oldValue)。这个合并方法允许用户他们指定想如何处理多个值关联到同一个键的冲突。在下面展示的代码中,我们只是使用了新的值,当然你也可以编写一个智能的算法来处理冲突。

private static Map<String, Task> taskMap_duplicates(List<Task> tasks) {
  return tasks.stream().collect(toMap(Task::getTitle, identity(), (t1, t2) -> t2));
}

你可以通过使用toMap方法的第三个变体来指定其他的映射实现。这需要你指定将用来存储结果的Map和Supplier。

public Map<String, Task> collectToMap(List<Task> tasks) {
    return tasks.stream().collect(toMap(Task::getTitle, identity(), (t1, t2) -> t2, LinkedHashMap::new));
}

2. 按照key排序

public class SortByKeyExample {
 
    public static void main(String[] argv) {
 
        Map<String, Integer> unsortMap = new HashMap<>();
        unsortMap.put("z", 10);
        unsortMap.put("b", 5);
        unsortMap.put("a", 6);
        unsortMap.put("c", 20);
        unsortMap.put("d", 1);
        unsortMap.put("e", 7);
        unsortMap.put("y", 8);
        unsortMap.put("n", 99);
        unsortMap.put("g", 50);
        unsortMap.put("m", 2);
        unsortMap.put("f", 9);
 
        System.out.println("Original...");
        System.out.println(unsortMap);
 
        // sort by keys, a,b,c..., and return a new LinkedHashMap
        // toMap() will returns HashMap by default, we need LinkedHashMap to keep the order.
        Map<String, Integer> result = unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
 
        // Not Recommend, but it works.
        // Alternative way to sort a Map by keys, and put it into the "result" map
        Map<String, Integer> result2 = new LinkedHashMap<>();
        unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));
 
        System.out.println("Sorted...");
        System.out.println(result);
        System.out.println(result2);
    }
}

输出:

Original...
{a=6, b=5, c=20, d=1, e=7, f=9, g=50, y=8, z=10, m=2, n=99}

Sorted...
{a=6, b=5, c=20, d=1, e=7, f=9, g=50, m=2, n=99, y=8, z=10}
{a=6, b=5, c=20, d=1, e=7, f=9, g=50, m=2, n=99, y=8, z=10}

3. 按照value排序​​​​​​​

public class SortByValueExample {
 
    public static void main(String[] argv) {
 
        Map<String, Integer> unsortMap = new HashMap<>();
        unsortMap.put("z", 10);
        unsortMap.put("b", 5);
        unsortMap.put("a", 6);
        unsortMap.put("c", 20);
        unsortMap.put("d", 1);
        unsortMap.put("e", 7);
        unsortMap.put("y", 8);
        unsortMap.put("n", 99);
        unsortMap.put("g", 50);
        unsortMap.put("m", 2);
        unsortMap.put("f", 9);
 
        System.out.println("Original...");
        System.out.println(unsortMap);
 
        // sort by values, and reserve it, 10,9,8,7,6...
        Map<String, Integer> result = unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue, LinkedHashMap::new));
 
        // Alternative way
        Map<String, Integer> result2 = new LinkedHashMap<>();
        unsortMap.entrySet().stream()
                .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
                .forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));
 
        System.out.println("Sorted...");
        System.out.println(result);
        System.out.println(result2);
    }
}

输出:

Original...
{a=6, b=5, c=20, d=1, e=7, f=9, g=50, y=8, z=10, m=2, n=99}

Sorted...
{n=99, g=50, c=20, z=10, f=9, y=8, e=7, a=6, b=5, m=2, d=1}
{n=99, g=50, c=20, z=10, f=9, y=8, e=7, a=6, b=5, m=2, d=1}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 原链接:http://www.cnblogs.com/langtianya/p/3757993.html JDK各...
    把爱放下会走更远阅读 1,133评论 0 10
  • Java 8的新特性可以帮助你: 1.使用Java 8可以减少冗长的代码,让代码更易于理解 2.通过方法引用和St...
    Phoenix小彬阅读 971评论 0 2
  • JDK各个版本的新特性 对于很多刚接触java语言的学者来说,要了解一门语言,最好的方式是从基础的版本进行理解,升...
    小庄bb阅读 1,164评论 0 1
  • 对于Java开发者来说,Java8的版本显然是一个具有里程碑意义的版本,蕴含了许多令人激动的新特性,如果能利用好这...
    jackcooper阅读 1,041评论 0 6
  • Stream是Java 8 提供的高效操作集合类(Collection)数据的API。 1. 从Iterator到...
    nkcoder阅读 5,671评论 2 24