sort By Value in Map Descending - Java Collection Framework

Java examples for Collection Framework:Map

Description

sort By Value in Map Descending

Demo Code


    //package com.java2s;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.LinkedHashMap;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;

    public class Main {
        public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueDescending(Map<K, V> map) {
   return sortByValue(map, (o1, o2) -> o2.getValue().compareTo(o1.getValue()));
}

        private static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(
                Map<K, V> map, Comparator<Map.Entry<K, V>> comparator) {

            List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
            Collections.sort(list, comparator);

            Map<K, V> result = new LinkedHashMap<>();
            for (Map.Entry<K, V> entry : list) {
                result.put(entry.getKey(), entry.getValue());
            }//  w  ww.  j  ava  2  s. co  m

            return result;
        }
    }

Related Tutorials