Here you can find the source of sortMapDescendingByValue(Map
Parameter | Description |
---|---|
unsortedMap | the unsortedMap |
public static <K, V extends Comparable<V>> Map<K, V> sortMapDescendingByValue(Map<K, V> unsortedMap)
//package com.java2s; /* *********************************************************************** * * project: org.matsim.*/*from w w w . j av a2 s .co m*/ * *********************************************************************** * * * * copyright : (C) 2016 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.*; public class Main { /** * Sorts a map by its values. * * @param unsortedMap the unsortedMap * @return the sorted map */ public static <K, V extends Comparable<V>> Map<K, V> sortMapDescendingByValue(Map<K, V> unsortedMap) { // Convert Map to List List<Map.Entry<K, V>> list = new LinkedList<>(unsortedMap.entrySet()); // Sort list with comparator, to compare the Map values Collections.sort(list, (o1, o2) -> -(o1.getValue()).compareTo(o2.getValue())); // Convert sorted map back to a Map Map<K, V> sortedMap = new LinkedHashMap<>(); for (Map.Entry<K, V> entry : list) { sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; } }