java8 实现map以value值排序

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.LinkedHashMap;

public class MapSorted{

    public static void main(String[] args) {
        
        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);
        
        System.out.println(map);

        //如果value为java对象,则需要实现Comparable接口,重写compareTo方法

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

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

        System.out.println(sortedMap);

        //DESC Collections.reverseOrder ||  reversed()
        map.entrySet().stream()
        .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
        .forEachOrdered(x -> sortedMap2.put(x.getKey(), x.getValue()));

        // 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);
    }
}
{A=3, B=5, C=1, D=1, E=9}
{C=1, D=1, A=3, B=5, E=9}
{E=9, B=5, A=3, C=1, D=1}
{E=9, B=5, A=3, C=1, D=1}

 

    原文作者:Haiyoung
    原文地址: https://blog.csdn.net/haiyoung/article/details/82694215
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞