Java tutorial
//package com.java2s; /* *********************************************************************** * * project: org.matsim.* * CollectionUtils.java * * * *********************************************************************** * * * * copyright : (C) 2011 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ 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, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) { return sortByValue(map, false); } public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean decesnding) { int s2 = 1; if (decesnding) s2 = -1; final int sign = s2; List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet()); Collections.sort(list, new Comparator<Map.Entry<K, V>>() { @Override public int compare(Entry<K, V> o1, Entry<K, V> o2) { return sign * o1.getValue().compareTo(o2.getValue()); } }); Map<K, V> sorted = new LinkedHashMap<>(); for (Map.Entry<K, V> entry : list) { sorted.put(entry.getKey(), entry.getValue()); } return sorted; } }