Here you can find the source of sortMapByValue(Map
Parameter | Description |
---|---|
map | The map |
comparator | The comparator to sort the map |
K | The key type |
V | The value type |
public static <K, V> Map<K, V> sortMapByValue(Map<K, V> map, Comparator<Map.Entry<K, V>> comparator)
//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; } }