Here you can find the source of sortByValues(Map
public static <K extends Comparable, V extends Comparable> Map<K, V> sortByValues(Map<K, V> map)
//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 <K extends Comparable, V extends Comparable> Map<K, V> sortByValues(Map<K, V> map) { List<Map.Entry<K, V>> entries = new LinkedList<Map.Entry<K, V>>(map.entrySet()); Collections.sort(entries, new Comparator<Map.Entry<K, V>>() { @Override//from ww w. j a v a2s. c o m public int compare(Entry<K, V> o1, Entry<K, V> o2) { float val1 = Float.parseFloat(o1.getValue().toString()); float val2 = Float.parseFloat(o2.getValue().toString()); if (val1 > val2) return -1; else if (val1 < val2) return 1; else return 0; } }); //LinkedHashMap will keep the keys in the order they are inserted //which is currently sorted on natural ordering Map<K, V> sortedMap = new LinkedHashMap<K, V>(); for (Map.Entry<K, V> entry : entries) { sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; } }