java8 實現map以value值排序

Haiyoung發表於2018-09-13
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}

 

相關文章