Here you can find the source of sortByValues(Map
public static <T, R> Map<T, R> sortByValues(Map<T, R> map)
//package com.java2s; //License from project: Open Source License import java.util.*; public class Main { public static <T, R> Map<T, R> sortByValues(Map<T, R> map) { List list = new LinkedList<>(map.entrySet()); // Defined Custom Comparator here Collections.sort(list, Map.Entry.comparingByValue().reversed()); // Here I am copying the sorted list in HashMap // using LinkedHashMap to preserve the insertion order HashMap<T, R> sortedHashMap = new LinkedHashMap<>(); for (Iterator it = list.iterator(); it.hasNext();) { Map.Entry<T, R> entry = (Map.Entry<T, R>) it.next(); sortedHashMap.put(entry.getKey(), entry.getValue()); }/* w ww . j a v a 2 s . co m*/ return sortedHashMap; } }