Tree map sort by key and sort by value

package com.emiza.utility;

import java.util.Comparator;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;

public class Test {
public static void main(String[] args) {
Map<Integer, String> map = new TreeMap<Integer, String>();
map.put(1, "one");
map.put(3, "athree");
map.put(2, "two");
// prints one two three 
for(Integer key : map.keySet()) {
    System.out.println(map.get(key));
}

System.out.println(entriesSortedByValues(map));
}

static <K,V extends Comparable<? super V>>
SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
    SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
        new Comparator<Map.Entry<K,V>>() {
            @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                int res = e1.getValue().compareTo(e2.getValue());
                return res != 0 ? res : 1;
            }
        }
    );
    sortedEntries.addAll(map.entrySet());
    return sortedEntries;
}
}

Comments