Java Map Sort sortMapByValue(Map map, Comparator> comparator)

Here you can find the source of sortMapByValue(Map map, Comparator> comparator)

Description

Sorts given map by given comparator

License

Open Source License

Parameter

Parameter Description
map The map
comparator The comparator to sort the map
K The key type
V The value type

Return

The sorted map

Declaration

public static <K, V> Map<K, V> sortMapByValue(Map<K, V> map, Comparator<Map.Entry<K, V>> comparator) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.*;

public class Main {
    /**/*from   w ww . j  av a2 s  .c  o m*/
     * Sorts given map by given comparator
     *
     * @param map        The map
     * @param comparator The comparator to sort the map
     * @param <K>        The key type
     * @param <V>        The value type
     * @return The sorted map
     */
    public static <K, V> Map<K, V> sortMapByValue(Map<K, V> map, Comparator<Map.Entry<K, V>> comparator) {
        List<Map.Entry<K, V>> list = new LinkedList<>(map.entrySet());
        list.sort(comparator);

        Map<K, V> result = new LinkedHashMap<>();
        for (Map.Entry<K, V> entry : list) {
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    }
}

Related

  1. sortMapByKey(Map data)
  2. sortMapByKey(Map map)
  3. sortMapByValue(Map input, final boolean desc)
  4. sortMapByValue(Map map, Comparator comparator)
  5. sortMapByValue(Map map, Comparator> valueComparator)
  6. sortMapByValue(Map map, final boolean descending)
  7. sortMapByValue(Map oriMap)
  8. sortMapByValue(Map unsortMap, boolean highFirst)
  9. sortMapByValue(Map oriMap)