How to sort a treemap based on its values?

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

    You could try giving a Comparator that compare values instead of keys when you create the TreeMap.

        final TreeMap tree = new TreeMap();
        tree.put(1, "1");
        tree.put(2, "2");
        tree.put(3, "3");
        tree.put(4, "4");
    
        final TreeMap treeSortedByValues = new TreeMap(new Comparator()
        {
            public int compare(Integer o1, Integer o2)
            {
                return tree.get(o1).compareTo(tree.get(o2));
            }
        });
        treeSortedByValues.putAll(tree);
    
        for ( Entry e : treeSortedByValues.entrySet() )
        {
            System.out.println(e.getKey() + ": " + e.getValue());
        }
    

提交回复
热议问题