Here you can find the source of sortedByValues(Map
Parameter | Description |
---|---|
map | a parameter |
public static <K, V extends Comparable<? super V>> SortedSet<Entry<K, V>> sortedByValues(Map<K, V> map, final boolean asc)
//package com.java2s; //License from project: LGPL import java.util.Comparator; import java.util.Map; import java.util.Map.Entry; import java.util.SortedSet; import java.util.TreeSet; public class Main { /**/*from w ww . j a va 2s. c o m*/ * sort a map by value * * @param map * @return */ public static <K, V extends Comparable<? super V>> SortedSet<Entry<K, V>> sortedByValues(Map<K, V> map, final boolean asc) { SortedSet<Map.Entry<K, V>> sortedEntries = new TreeSet<Map.Entry<K, V>>(new Comparator<Map.Entry<K, V>>() { public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2) { int compareTo = e1.getValue().compareTo(e2.getValue()); int direct = 1; if (!asc) { direct = -1; } return compareTo * direct; } }); sortedEntries.addAll(map.entrySet()); return sortedEntries; } }