Here you can find the source of sortByValue(Map
Parameter | Description |
---|---|
map | the map to be sorted |
public static <K extends Object, V extends Object> Map<K, V> sortByValue(Map<K, V> map)
//package com.java2s; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; public class Main { /**// ww w. ja v a 2 s . co m * Sort the value in the map and swap the pair of view * and its rank value in descending order. * * @param map the map to be sorted * @return the sorted map */ public static <K extends Object, V extends Object> Map<K, V> sortByValue(Map<K, V> map) { return sortByValue(map, true); } /** * Sort the value in the map and swap the pair of view * and its rank value in descending order. * * @param map the map to be sorted * @return the sorted map */ public static <K extends Object, V extends Object> Map<K, V> sortByValue(Map<K, V> map, final boolean isDecrease) { List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet()); Collections.sort(list, new Comparator<Object>() { @SuppressWarnings("unchecked") public int compare(Object o1, Object o2) { int compareValue = ((Comparable<V>) ((Map.Entry<K, V>) (o1)).getValue()) .compareTo(((Map.Entry<K, V>) (o2)).getValue()); // reverse the order if (isDecrease) { if (compareValue == -1) compareValue = 1; else if (compareValue == 1) compareValue = -1; } else { if (compareValue == 1) compareValue = 1; else if (compareValue == -1) compareValue = -1; } return compareValue; } }); Map<K, V> result = new LinkedHashMap<K, V>(); for (Iterator<Map.Entry<K, V>> it = list.iterator(); it.hasNext();) { Map.Entry<K, V> entry = (Map.Entry<K, V>) it.next(); result.put(entry.getKey(), entry.getValue()); } return result; } }