How to Sort Map past times values inwards Java eight using Lambdas together with Stream - Example Tutorial

In past, I receive got shown y'all how to form a HashMap past times values inwards Java, but that was using traditional techniques of pre-Java 8 world. Now the fourth dimension has changed together with Java has evolved into a programming linguistic communication which too has the mightiness of functional programming. How tin flaming y'all bring payoff of that fact to practise your solar daytime to solar daytime chore e.g. how practise y'all form a Map past times values inwards Java using lambda expressions together with Stream API. That's what y'all are going to larn inwards this article. It volition serve 2 purposes, first, it volition tell y'all a novel way to form a Map past times values inwards Java, and, minute together with to a greater extent than of import it volition innovate y'all to essential Java 8 features similar lambda expression together with streams.

By the way, it's non exactly the lambda seem together with flow which makes coding fun inwards Java 8, but too all the novel API methods added into existing interface e.g. Comparator, Map.Entry which makes day-to-day coding much easier.

This evaluation of existing interfaces was possible past times introducing non-abstract method on interface e.g. default methods together with static methods.

Because of this path breaking feature, it's possible to add together novel methods into existing Java interface together with Java API designers receive got taken payoff to add together much-needed methods on pop existing interfaces.

One of the best examples of this is java.util.Comparator interface which has straight off got comparing() together with thenComparing() methods to chain multiple comparators, making it easier to compare an object past times multiple fields.

The Map.Entry class, which is a nested static degree of java.util.Map interface is too non behind, it has got 2 additional methods comparingByKey() together with comparingByValue() which tin flaming live used to form a Map past times fundamental together with values. They tin flaming live used  along alongside sorted() method of Stream to sort an HashMap past times values inwards Java.




Sorting Map past times values on Increasing order

You tin flaming form a Map e.g. an HashMap, LinkedHashMap, or TreeMap inwards Java 8 past times using the sorted() method of java.util.stream.Stream class. These way accepts a Comparator, which tin flaming live used for sorting. If y'all desire to form past times values together with so y'all tin flaming exactly utilization the comparingByValue() method of the Map.Entry class. This method is newly added inwards Java 8 to acquire far easier for sorting.

ItemToPrice.entrySet() .stream() .sorted(Map.Entry.<String, Integer>comparingByValue()) .forEach(System.out::println);

Btw, if y'all demand a Map instead of exactly printing the value into the console, y'all tin flaming collect the number of the sorted flow using collect() method of Stream together with Collectors degree of Java 8 equally shown below:

// now, let's collect the sorted entries inwards Map Map<String, Integer> sortedByPrice = ItemToPrice.entrySet() .stream() .sorted(Map.Entry.<String, Integer>comparingByValue()) .collect(Collectors.toMap(e -> e.getKey(),e -> e.getValue()));

The Map returned past times the previous declaration was non sorted because ordering was lost spell collecting number inwards Map y'all demand to utilization the LinkedHashMap to save the order

Map<String, Integer> sortedByValue = ItemToPrice.entrySet() .stream() .sorted(Map.Entry.<String, Integer>comparingByValue()) .collect(toMap(Map.Entry::getKey,                Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

This is the right way to form a Map past times values inwards Java 8 because straight off the ordering volition non live lost equally Collector is using LinkedHashMap to shop entries. This is too a adept event of using constructor reference inwards Java 8. You tin flaming read to a greater extent than nigh that inwards whatsoever adept Java 8 majority e.g. Java 8 inwards Action or Java SE 8 for Really Impatient past times Cay S. Horstmann.



Sorting Map past times values on decreasing Order

In guild to form a Map past times values inwards decreasing order, nosotros exactly demand to move past times a Comparator which form it inwards the contrary order. You tin flaming utilization the reversed() method of java.util.Comparator purpose to reverse order of a Comparator. This method is too newly added inwards the Comparator degree inwards JDK 8.

Map<String, Integer> sortedByValueDesc = ItemToPrice.entrySet() .stream() .sorted(Map.Entry.<String, Integer>comparingByValue().reversed()) .collect(toMap(Map.Entry::getKey,                 Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

The fundamental indicate hither is the utilization of reversed() method, residual of the code is same equally the previous example. In the outset mensuration y'all acquire the entry laid upward from the Map, together with so y'all acquire the stream, together with so y'all sorted elements of the flow using sorted() method, which needs a comparator.

You render a Comparator which compares past times values together with and so reversed it so that entries volition live ordered inwards the decreasing order. Finally, y'all collected all elements into a Map together with y'all asked Collector to utilization the LinkedHashMap past times using constructor reference, which is similar to method reference inwards Java 8 but instead of using method mention nosotros exactly utilization Class::new, that's it.




Important points to Remember

Here are roughly of the of import points to think spell sorting a Map past times values inwards Java 8. These are really of import for correctly sorting whatsoever HashMap or Hashtable equally well:
  1. Use LinkedHashMap for collecting the number to proceed the sorting intact.
  2. Use static import for meliorate readability e.g. static import Map.Entry nested class.
  3. Use novel comparingByKey() together with comparingByValue() method from Map.Entry they were added inwards Java 8 to brand sorting past times fundamental together with value easier inwards Java. 
  4. Use reversed() method to form the Map inwards descending order
  5. Use forEach() to impress the Map
  6. Use Collectors to collect the number into a Map but ever utilization LinkedHashMap because it maintains the insertion order. 
You tin flaming larn to a greater extent than nigh lambda seem together with method reference used inwards our event inwards a adept Java 8 majority e.g. Java SE 8 for Really Impatient past times Cay S. Horstmann.



Java Program to Sort the Map past times Values inwards JDK 8

Here is our consummate Java programme to form a HashMap past times values inwards Java 8 using a lambda expression, method reference, together with novel methods introduced inwards JDK 8 e.g. Map.Entry.comparingByValue() method, which makes it easier to form the Map past times values.

/*  * To alter this license header, direct License Headers inwards Project Properties.  * To alter this template file, direct Tools | Templates  * together with opened upward the template inwards the editor.  */ package test;  import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; import static java.util.stream.Collectors.*;  /**  *  * @author Javin Paul  */ public class SortingMapByValueInJava8 {    /**    * @param args    * the ascendency business arguments    */   public static void main(String[] args) {      // Creating a Map alongside electoric items together with prices     Map<String, Integer> ItemToPrice = new HashMap<>();     ItemToPrice.put("Sony Braiva", 1000);     ItemToPrice.put("Apple iPhone 6S", 1200);     ItemToPrice.put("HP Laptop", 700);     ItemToPrice.put("Acer hard disk drive Monitor", 139);     ItemToPrice.put("Samsung Galaxy", 800);      System.out.println("unsorted Map: " + ItemToPrice);      // sorting Map past times values inwards ascending order, cost here     ItemToPrice.entrySet().stream()         .sorted(Map.Entry.<String, Integer> comparingByValue())         .forEach(System.out::println);      // now, let's collect the sorted entries inwards Map     Map<String, Integer> sortedByPrice = ItemToPrice.entrySet().stream()         .sorted(Map.Entry.<String, Integer> comparingByValue())         .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));      System.out.println("Map incorrectly sorted past times value inwards ascending order: "         + sortedByPrice);      // the Map returned past times the previous declaration was non sorted     // because ordering was lost spell collecting number inwards Map     // y'all demand to utilization the LinkedHashMap to save the order      Map<String, Integer> sortedByValue = ItemToPrice         .entrySet()         .stream()         .sorted(Map.Entry.<String, Integer> comparingByValue())         .collect(             toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1,                 LinkedHashMap::new));      System.out.println("Map sorted past times value inwards increasing order: "         + sortedByValue);      // sorting a Map past times values inwards descending order     // exactly contrary the comparator sorting past times using reversed() method     Map<String, Integer> sortedByValueDesc = ItemToPrice         .entrySet()         .stream()         .sorted(Map.Entry.<String, Integer> comparingByValue().reversed())         .collect(             toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1,                 LinkedHashMap::new));      System.out.println("Map sorted past times value inwards descending order: "         + sortedByValueDesc);   }  } Output unsorted Map: {Samsung Galaxy=800, HP Laptop=700, Sony Braiva=1000,                Acer HD Monitor=139, Apple iPhone 6S=1200} Acer HD Monitor=139 HP Laptop=700 Samsung Galaxy=800 Sony Braiva=1000 Apple iPhone 6S=1200 Map incorrectly sorted past times value inwards ascending order:  {Samsung Galaxy=800, HP Laptop=700, Sony Braiva=1000,  Acer HD Monitor=139, Apple iPhone 6S=1200} Map sorted past times value inwards increasing order:  {Acer HD Monitor=139, HP Laptop=700, Samsung Galaxy=800,  Sony Braiva=1000, Apple iPhone 6S=1200} Map sorted past times value inwards descending order: {Apple iPhone 6S=1200,  Sony Braiva=1000, Samsung Galaxy=800, HP Laptop=700, Acer HD Monitor=139}


You tin flaming encounter that map is sorted past times values, which are integers. In this outset example, nosotros receive got printed all entries inwards sorted guild together with that's why Acer hard disk drive Monitor comes outset because it is to the lowest degree expensive, spell Apple iPhone comes final because it is most expensive.


In the minute example, fifty-fifty though nosotros sorted inwards the same way equally before, the goal number is non what y'all receive got expected because nosotros failed to collect the number into a Map which keeps them inwards the guild they were i.e. nosotros should receive got used LinkedHashMap, which keeps entries inwards the guild they were inserted.

In the 3rd together with 4th example, nosotros rectified our error together with collected the number of the sorted flow into a LinkedHashMap, therefore nosotros receive got entries inwards sorted order. The final example, sort entries inwards descending order hence, Apple comes outset together with Acer comes last.

Here is a i liner inwards Java 8 to form a HashMap past times values:
 but that was using traditional techniques of pre How to Sort Map past times values inwards Java 8 using Lambdas together with Stream - Example Tutorial


That's all nigh how to form a Map past times values inwards Java 8. y'all tin flaming utilization this technique to form whatsoever Map implementations e.g. HashMap, Hashtable, ConcurrentHashMap, TreeMap etc. If y'all don't demand to impress the values or perform whatsoever operation, but y'all exactly demand a sorted Map together with so brand certain y'all utilization collect() method to shop sorted entries into roughly other Map. Also, when y'all utilization the Collector to collect chemical component from sorted Stream, brand certain y'all utilization LinkedHashMap to collect the result, otherwise ordering volition live lost.


Further Reading
What's New inwards Java 8
Java SE 8 for Really Impatient


Related Java 8 Tutorials
If y'all are interested inwards learning to a greater extent than nigh novel features of Java 8, hither are my before articles roofing roughly of the of import concepts of Java 8:
  • 20 Examples of Date together with Time inwards Java 8 (tutorial)
  • How to bring together String inwards Java 8 (example)
  • How to utilization filter() method inwards Java 8 (tutorial)
  • 5 Books to Learn Java 8 from Scratch (books)
  • How to utilization Stream degree inwards Java 8 (tutorial)
  • How to utilization forEach() method inwards Java 8 (example)
  • How to convert List to Map inwards Java 8 (solution)
  • How to utilization peek() method inwards Java 8 (example)

Thanks for reading this tutorial so far. If y'all similar this event of sorting HashMap inwards Java 8 using lambda seem together with so delight part alongside your friends together with colleagues. If y'all receive got whatsoever question, feedback, or proposition together with so delight drib a comment.

Subscribe to receive free email updates:

0 Response to "How to Sort Map past times values inwards Java eight using Lambdas together with Stream - Example Tutorial"

Posting Komentar