Stream流实现 map 以 value 值排序

  • Post author:
  • Post category:其他


随机建立一个需要排序的map:

Map<String, Integer> map = new HashMap<>();
        map.put("A", 3);
        map.put("B", 5);
        map.put("C", 1);
        map.put("D", 1);
        map.put("E", 9);

创建两个LinkedHashMap备用,LinkedHashMap会按照插入的先后顺序进行排序:

Map<String, Integer> sortedMap = new LinkedHashMap<>();
Map<String, Integer> sortedMap2 = new LinkedHashMap<>();

升序(ASC):

map.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())
                .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));

System.out.println(sortedMap);

结果:

{C=1, D=1, A=3, B=5, E=9}

降序(DESC):

//第一种    Collections.reverseOrder
map.entrySet().stream()
                .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
                .forEachOrdered(x -> sortedMap2.put(x.getKey(), x.getValue()));

//第二种    reversed()
map.entrySet().stream()
         .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
         .forEachOrdered(x -> sortedMap2.put(x.getKey(), x.getValue()));


System.out.println(sortedMap2);


//Collectors.toMap 直接返回排好序的 map
map = map.entrySet().stream()
                .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
                .collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue(), (x1, x2) -> x2, LinkedHashMap::new));

map = map.entrySet().stream()
                .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (x1, x2) -> x2, LinkedHashMap::new));
        System.out.println(map);

结果:

{E=9, B=5, A=3, C=1, D=1}



版权声明:本文为m0_69237510原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。