java8 实现map以value值排序

人盡茶涼 提交于 2020-08-06 06:28:46

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!