Here you can find the source of sortByValues(Map map, final Comparator comp)
public static <A, B> Map<A, B> sortByValues(Map<A, B> map, final Comparator<B> comp)
//package com.java2s; //License from project: Open Source License import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class Main { public static <A, B> Map<A, B> sortByValues(Map<A, B> map, final Comparator<B> comp) { List<Map.Entry<A, B>> entries = new LinkedList<Entry<A, B>>( map.entrySet());// w w w. ja va 2s .co m Collections.sort(entries, new Comparator<Map.Entry<A, B>>() { @Override public int compare(Entry<A, B> o1, Entry<A, B> o2) { return comp.compare(o1.getValue(), o2.getValue()); } }); Map<A, B> out = new LinkedHashMap<A, B>(); for (Map.Entry<A, B> e : entries) { out.put(e.getKey(), e.getValue()); } return out; } }