Sorts a Map by it's value - Java java.util

Java examples for java.util:Map Value

Description

Sorts a Map by it's value

Demo Code


//package com.java2s;

import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Stream;

public class Main {
  /**/*from  w w w  .jav  a 2s. co  m*/
   * Sorts a Map by it's value
   *
   * @param map
   *          Map
   * @param <K>
   *          Key
   * @param <V>
   *          Value
   * @return The sorted map
   */
  public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    Map<K, V> result = new LinkedHashMap<>();
    Stream<Map.Entry<K, V>> st = map.entrySet().stream();

    st.sorted(Comparator.comparing(Map.Entry::getValue)).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));

    return result;
  }
}

Related Tutorials