Sunday, July 14, 2019

How To Sort HashMap using stream in java 8

Sort HashMap by values in ascending and descending order using stream api.

Important points to Remember
There are some points to remember once you are sorting a map by value using stream api.

  • We should Use LinkedHashMap for collecting the result to keep the sorting intact.
  • Use static import for better readability e.g. static import Map.Entry nested class.
  • We should use method from Map.Entry like comparingByValue() and comparingByKey() which was added in Java to make sorting by key and value in Java 8.
  •  To sort map in descending order use reversed() method. 
  • To print map use forEach()
  • Use Collectors to collect the result into a Map but always use LinkedHashMap because it maintains the insertion order. 


package com.shubh.stream.list.to.map;

import java.util.*;
import java.util.stream.*;

public class MapToStream {

 public static <K, V> Stream<Map.Entry<K, V>> convertMapToStream(Map<K, V> map) {
  return map.entrySet().stream();
 }

 public static void main(String args[]) {

  Map<Integer, String> map = new HashMap<>();
  map.put(1, "Sandeep");
  map.put(2, "Suman");
  map.put(3, "Aman");
  map.put(4, "Kamal");
  map.put(5, "Raj");

  // Print the Map
  System.out.println("Map: " + map);

  // Convert the Map to Stream
  // Stream<Map.Entry<Integer, String>> stream = map.entrySet().stream();

  // Convert the Map to Stream using keySet()
  // Stream<Integer> streamKey = map.keySet().stream();
  
  // Convert the Map to Stream using values()
  // Stream<String> streamValue = map.values().stream();

  // Print
  // System.out.println("Stream: " + Arrays.toString(stream.toArray()));

  // Compare By Value and print.
  map.entrySet().stream().sorted(Map.Entry.<Integer, String>comparingByValue()).forEach(System.out::println);

  // collect the sorted entries in Map
  System.out.println("// collect the sorted entries in Map");
  Map<Integer, String> sortedByValue = map.entrySet().stream()
    .sorted(Map.Entry.<Integer, String>comparingByValue())
    .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));

  sortedByValue.forEach((key, value) -> System.out.println("Key: " + key + " Value: " + value));

  System.out.println("// collect the sorted entries in Map");
  Map<Integer, String> sortedByValue2 = map.entrySet().stream()
    .sorted(Map.Entry.<Integer, String>comparingByValue())
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

  sortedByValue2.forEach((key, value) -> System.out.println("Key: " + key + " Value: " + value));

  // Sorting Map by values on decreasing Order
  System.out.println("//Sorting Map by values on decreasing Order");
  Map<Integer, String> sortedByValueDesc = map.entrySet().stream()
    .sorted(Map.Entry.<Integer, String>comparingByValue().reversed())
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

  sortedByValueDesc.forEach((key, value) -> System.out.println("Key: " + key + " Value: " + value));

 }
}
Output

Map: {1=Sandeep, 2=Suman, 3=Aman, 4=Kamal, 5=Raj}
3=Aman
4=Kamal
5=Raj
1=Sandeep
2=Suman
// collect the sorted entries in Map
Key: 1 Value: Sandeep
Key: 2 Value: Suman
Key: 3 Value: Aman
Key: 4 Value: Kamal
Key: 5 Value: Raj
// collect the sorted entries in Map
Key: 3 Value: Aman
Key: 4 Value: Kamal
Key: 5 Value: Raj
Key: 1 Value: Sandeep
Key: 2 Value: Suman
//Sorting Map by values on decreasing Order
Key: 2 Value: Suman
Key: 1 Value: Sandeep
Key: 5 Value: Raj
Key: 4 Value: Kamal
Key: 3 Value: Aman




Related Tutorial

No comments:

Post a Comment