Java Map Sort sortMapDescendingByValue(Map unsortedMap)

Here you can find the source of sortMapDescendingByValue(Map unsortedMap)

Description

Sorts a map by its values.

License

Open Source License

Parameter

Parameter Description
unsortedMap the unsortedMap

Return

the sorted map

Declaration

public static <K, V extends Comparable<V>> Map<K, V> sortMapDescendingByValue(Map<K, V> unsortedMap) 

Method Source Code


//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;
    }
}

Related

  1. sortMapByValues(Map map, final boolean inverted)
  2. sortMapByValuesDecreasing( final Map mapToSort)
  3. sortMapByValuesDescending( Map aMap)
  4. sortMapDesc(Map map)
  5. sortMapDescByValue(Map map)
  6. sortMapUsingComparator(final Map map, final Comparator comparator)
  7. sortParams(Map params)
  8. sortSimilarityMapByValue(SortedMap temp)
  9. sortValue(Map toSort, boolean descending, final boolean thenByKey)