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

public class Main {

    public static void main(String[] args) {

        Map<String, String> map = new HashMap<String, String>();
    	
    	map.put("My", "World!");
    	map.put("Hello", "World!");
    	map.put("This", "World!");
    	map.put("Test", "X!");
    	
    	System.out.println("The original map: " + map);

    	// sort the 
    	SortedSet<Map.Entry<String, String>> sorted = entriesSortedByValues(map);

    	// print the value based sorted set
    	System.out.println("The sorted set:   " + sorted);
    	
        // check that for example the first element is in the set
    	if (!sorted.contains(sorted.iterator().next()))
        	throw new RuntimeException("The set doesn't contain the first element?");
    }
    
    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; // Special fix to preserve items with equal values
                }
            }
        );
        sortedEntries.addAll(map.entrySet());
        return sortedEntries;
    }
}