Java Map Sort sortByValue(Map map)

Here you can find the source of sortByValue(Map map)

Description

Sort a map by its values

License

Open Source License

Parameter

Parameter Description
S Key type
T Value type
map The map to sort

Return

The map, sorted by its values

Declaration

public static <S, T extends Comparable<T>> Map<S, T> sortByValue(Map<S, T> map) 

Method Source Code

//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;
    }
}

Related

  1. sortByValue(Map map)
  2. sortByValue(Map map)
  3. sortByValue(Map map)
  4. sortByValue(Map map, boolean descending)
  5. sortByValue(Map map, final boolean asc)
  6. sortByValue(Map map)
  7. sortByValueAscending(Map map)
  8. sortByValueDESC(Map map)
  9. sortByValueDescending( Map map)