How to sort a treemap based on its values?

前端 未结 9 1009
萌比男神i
萌比男神i 2020-12-01 04:53

How can I sort a treemap using its values rather than the key?

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 05:26

    Try below code it works fine for me. You can choose both ascending as well as descending order for sorting.

    package com.rais;
    
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.LinkedHashMap;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    
    public class SortMapByValue
    {
        public static boolean ASC = true;
        public static boolean DESC = false;
    
        public static void main(String[] args)
        {
    
            // Creating dummy unsorted map
            Map unsortMap = new HashMap();
            unsortMap.put("B", 55);
            unsortMap.put("A", 80);
            unsortMap.put("D", 20);
            unsortMap.put("C", 70);
    
            System.out.println("Before sorting......");
            printMap(unsortMap);
    
            System.out.println("After sorting ascending order......");
            Map sortedMapAsc = sortByComparator(unsortMap, ASC);
            printMap(sortedMapAsc);
    
    
            System.out.println("After sorting descindeng order......");
            Map sortedMapDesc = sortByComparator(unsortMap, DESC);
            printMap(sortedMapDesc);
    
        }
    
        private static Map sortByComparator(Map unsortMap, final boolean order)
        {
    
            List> list = new LinkedList>(unsortMap.entrySet());
    
            // Sorting the list based on values
            Collections.sort(list, new Comparator>()
            {
                public int compare(Entry o1,
                        Entry o2)
                {
                    if (order)
                    {
                        return o1.getValue().compareTo(o2.getValue());
                    }
                    else
                    {
                        return o2.getValue().compareTo(o1.getValue());
    
                    }
                }
            });
    
            // Maintaining insertion order with the help of LinkedList
            Map sortedMap = new LinkedHashMap();
            for (Entry entry : list)
            {
                sortedMap.put(entry.getKey(), entry.getValue());
            }
    
            return sortedMap;
        }
    
        public static void printMap(Map map)
        {
            for (Entry entry : map.entrySet())
            {
                System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
            }
        }
    }
    

提交回复
热议问题