Here you can find the source of sortByValue(Map
Parameter | Description |
---|---|
map | a map |
descending | if <tt>true</tt> the map is sorted descending, otherwise ascending |
K | the key type |
V | the value type |
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean descending)
//package com.java2s; /* *********************************************************************** * * project: org.matsim.*//www . j a v a 2 s .c o m * 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.*; import java.util.Map.Entry; public class Main { /** * Sorts a map by its values in ascending order. * * @param map a map * @param <K> the key type * @param <V> the value type * @return a new map */ public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) { return sortByValue(map, false); } /** * Sorts a map by its values. * * @param map a map * @param descending if <tt>true</tt> the map is sorted descending, otherwise ascending * @param <K> the key type * @param <V> the value type * @return a new map */ public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean descending) { int s2 = 1; if (descending) 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; } }