How to sort a treemap based on its values?

前端 未结 9 1011
萌比男神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:31

    Swap values and keys.

    More seriously, please provide some context what you want to achieve. Maybe it is enough to sort after other processing is finished.

    0 讨论(0)
  • 2020-12-01 05:34

    Here is a solution:

    public static <K, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {
        Comparator<K> valueComparator =  new Comparator<K>() {
            public int compare(K k1, K k2) {
                int compare = map.get(k2).compareTo(map.get(k1));
                if (compare == 0) return 1;
                else return compare;
            }
        };
        Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
        sortedByValues.putAll(map);
        return sortedByValues;
    }
    

    Note that the map is sorted from the highest value to the lowest.

    0 讨论(0)
  • 2020-12-01 05:35

    That's I have done this..

    package Collections;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.TreeMap;
    
    class MyComparator implements Comparator<Object> {
    
        public int compare(Object o1, Object o2) {
            return (((Integer) o2).compareTo((Integer) o1));
        }
    }
    
    class MyComparator1 implements Comparator<Object> {
        Map<Integer, String> map;
    
        public MyComparator1(Map<Integer, String> m) {
            this.map = m;
        }
    
        public int compare(Object o1, Object o2) {
            return (((String) map.get(o1)).compareTo((String) map.get(o2)));
        }
    }
    
    public class Map1 {
        public static void main(String[] args) {
            Map<Integer, String> hmap = new HashMap<Integer, String>();
            hmap.put(5, "Ashok");
            hmap.put(21, "Bhanu");
            hmap.put(7, "chaman");
            hmap.put(28, "dheeraj");
            hmap.put(761, "edison");
            hmap.put(1, "frank");
            hmap.put(-6, "gopal");
            hmap.put(78, "hari");
            System.out.println("Hash Map:" + hmap);
            Map<Integer, String> tmap = new TreeMap<>(hmap);
            System.out.println("Tree Map:" + tmap);
            MyComparator comp = new MyComparator();
            Map<Integer, String> itmap = new TreeMap<>(comp);
            itmap.putAll(hmap);
            System.out.println("Tree Map Inreverse order:" + itmap);
            Map<Integer, String> orderValuemap = new TreeMap<Integer, String>(new 
                MyComparator1(hmap));
                orderValuemap.putAll(hmap);
                orderValuemap.put(22,"hello");
            for(Entry<Integer, String> mp:orderValuemap.entrySet())
                System.out.println("Value : "+mp.getValue());
        }
    }
    
    0 讨论(0)
提交回复
热议问题