Here you can find the source of sortByValue(Map map)
Parameter | Description |
---|---|
S | Key type |
T | Value type |
map | The map to sort |
public static <S, T extends Comparable<T>> Map<S, T> sortByValue(Map<S, T> map)
//package com.java2s; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class Main { /**/* ww w .j av a 2 s. c om*/ * Sort a map by its values * * @param <S> Key type * @param <T> Value type * @param map The map to sort * @return The map, sorted by its values */ public static <S, T extends Comparable<T>> Map<S, T> sortByValue(Map<S, T> map) { List<Entry<S, T>> list = new LinkedList<Entry<S, T>>(map.entrySet()); Collections.sort(list, (o1, o2) -> o1.getValue().compareTo(o2.getValue())); Map<S, T> result = new LinkedHashMap<S, T>(); for (Entry<S, T> entry : list) { result.put(entry.getKey(), entry.getValue()); } return result; } }