Skip to content

Instantly share code, notes, and snippets.

@RICH0423
Last active September 21, 2017 02:38
Show Gist options
  • Select an option

  • Save RICH0423/7806e1b3a59e0de02ab66e87ed3e34ab to your computer and use it in GitHub Desktop.

Select an option

Save RICH0423/7806e1b3a59e0de02ab66e87ed3e34ab to your computer and use it in GitHub Desktop.
Sort Map by values in Java 8 using Lambdas and Stream
package com.rich.stream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import static java.util.stream.Collectors.*;
public class SortMapByValue {
public static void main(String[] args) {
// Creating a Map with electoric items and prices
Map<String, Integer> itemToPriceMap = new HashMap<>();
itemToPriceMap.put("Sony Braiva", 1000);
itemToPriceMap.put("Apple iPhone 6S", 1200);
itemToPriceMap.put("HP Laptop", 700);
itemToPriceMap.put("Acer HD Monitor", 139);
itemToPriceMap.put("Samsung Galaxy", 800);
System.out.println("Unsorted Map: " + itemToPriceMap);
Map<String, Integer> sortedByValueResult = sortByValue(itemToPriceMap);
System.out.println("Map sorted by value in increasing order: " + sortedByValueResult);
Map<String, Integer> sortedByValueDesc = sortByValueDesc(itemToPriceMap);
System.out.println("Map sorted by value in descending order: " + sortedByValueDesc);
}
private static Map<String, Integer> sortByValue(Map<String, Integer> map) {
return map.entrySet().stream()
.sorted(Map.Entry.<String, Integer> comparingByValue())
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}
private static Map<String, Integer> sortByValueDesc(Map<String, Integer> map) {
return map.entrySet().stream()
.sorted(Map.Entry.<String, Integer> comparingByValue().reversed())
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment