Here you can find the source of sortByValues( Map
@SuppressWarnings("rawtypes") public static <K extends Comparable, V extends Comparable> Map<K, V> sortByValues( Map<K, V> map)
//package com.java2s; //License from project: Apache 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 { @SuppressWarnings("rawtypes") 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());//from w ww . ja v a 2 s .co m Collections.sort(entries, new Comparator<Map.Entry<K, V>>() { @SuppressWarnings("unchecked") @Override public int compare(Entry<K, V> o1, Entry<K, V> o2) { return o1.getValue().compareTo(o2.getValue()); } }); //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) { //diki mou if if (Double.parseDouble(entry.getValue().toString()) != 0.0) { sortedMap.put(entry.getKey(), entry.getValue()); } } return sortedMap; } }