Friday, November 8, 2019

How To Kind Out Hashmap Past Times Values Inward Coffee Viii Using Lambdas In Addition To Flow - Illustration Tutorial

In the past, I receive got shown yous how to kind a HashMap past times values inward Java, but that was using traditional techniques of pre-Java 8 world. Now the fourth dimension has changed too Java has evolved into a programming linguistic communication which tin give the sack likewise practise functional programming. How tin give the sack you, a Java Programmer convey wages of that fact to practise your twenty-four hours to twenty-four hours work amend similar how practise yous kind a Map past times values inward Java using lambda expressions too Stream API. That's what yous are going to larn inward this article. It volition serve 2 purposes, first, it volition tell yous a novel way to kind a Map past times values inward Java, and, minute too to a greater extent than of import it volition innovate yous to essential Java 8 features similar Lambda Expression too Streams, which every Java Programmer should learn.

By the way, it's non exactly the lambda human face too flow which makes coding fun inward Java 8, but likewise all the novel API methods added into an existing interface like Comparator, Map.Entry which makes day-to-day coding much easier.

This evaluation of existing interfaces was possible past times introducing the non-abstract method on interfaces like default methods too static methods.

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

One of the best examples of this is java.util.Comparator interface which has straightaway got comparing() too thenComparing() methods to chain multiple comparators, making it easier to compare an object past times multiple fields, which was real boring too requires a lot of nesting prior to Java 8.

The Map.Entry class, which is a nested static class of java.util.Map interface is likewise non behind, it has got 2 additional methods comparingByKey() too comparingByValue() which tin give the sack live used to kind a Map past times cardinal too values. They tin give the sack live used along amongst sorted() method of Stream to sort a HashMap past times values inward Java.


Btw, if yous are novel into Java earth so I advise yous to start learning from Java 8 itself, no demand to larn the former techniques of doing a mutual work similar sorting a listing or map, working amongst appointment too time, etc too if yous demand some help, yous tin give the sack likewise appear at comprehensive online Java courses like The Complete Java MasterClass, which volition non exclusively learn yous all this but much more. It's likewise most up-to-date course, ever updated to encompass latest Java versions similar Java 11.




1. How to Sort Map past times values on Increasing order

You tin give the sack kind a Map similar a HashMap, LinkedHashMap, or TreeMap inward Java 8 past times using the sorted() method of java.util.stream.Stream class. These agency accepts a Comparator, which tin give the sack live used for sorting. If yous desire to kind past times values so yous tin give the sack exactly utilisation the comparingByValue() method of the Map.Entry class. This method is newly added inward Java 8 to acquire inward easier for sorting.

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

Btw, if yous demand a Map instead of exactly printing the value into the console, yous tin give the sack collect the number of the sorted flow using collect() method of Stream too Collectors shape of Java 8 every bit shown below:

// now, let's collect the sorted entries inward 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 inward Map yous demand to utilisation 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 kind a Map past times values inward Java 8 because straightaway the ordering volition non live lost every bit Collector is using LinkedHashMap to shop entries. This is likewise a proficient instance of using constructor reference inward Java 8. You tin give the sack read to a greater extent than well-nigh that inward the reverse order of a Comparator. This method is likewise newly added inward the Comparator shape inward 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 cardinal request hither is the utilisation of the reversed() method, the residue of the code is the same every bit the previous example. In the start mensuration yous acquire the entry ready from the Map, so yous acquire the stream, so yous sorted elements of the flow using sorted() method, which needs a comparator.

You render a Comparator which compares past times values too so reversed it so that entries volition live ordered inward the decreasing order. Finally, yous collected all elements into a Map too yous asked Collector to utilisation the LinkedHashMap past times using constructor reference, which is similar to method reference inward Java 8 but instead of using method mention it uses Class::new, that's it. If yous are interested, yous tin give the sack larn well-nigh it whatsoever proficient Java 8 majority like Java 8 inward Action or Java SE 8 for Really Impatient by Cay S. Horstmann.

 but that was using traditional techniques of pre How to kind HashMap past times values inward Java 8 using Lambdas too Stream - Example Tutorial




Important points to Remember

Here are some of the of import points to think spell sorting a Map past times values inward Java 8. These are real of import for correctly sorting whatsoever HashMap or Hashtable every bit well:
  1. Use LinkedHashMap for collecting the number to continue the sorting intact.
  2. Use static import for amend readability e.g. static import Map.Entry nested class.
  3. Use novel comparingByKey() too comparingByValue() method from Map.Entry they were added inward Java 8 to brand sorting past times cardinal too value easier inward Java.
     
  4. Use reversed() method to kind the Map inward descending order
  5. Use forEach() to impress the Map
  6. Use Collectors to collect the number into a Map but ever utilisation LinkedHashMap because it maintains the insertion order. 
You tin give the sack larn to a greater extent than well-nigh lambda human face too method reference used inward our instance inward a proficient Java 8 course of written report like The Complete Java MasterClass on Udemy.

 but that was using traditional techniques of pre How to kind HashMap past times values inward Java 8 using Lambdas too Stream - Example Tutorial




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

Here is our consummate Java programme to kind a HashMap past times values inward Java 8 using a lambda expression, method reference, too novel methods introduced inward JDK 8 like Map.Entry.comparingByValue() method, which makes it easier to kind the Map past times values.

/*  * To alter this license header, guide License Headers inward Project Properties.  * To alter this template file, guide Tools | Templates  * too opened upwardly the template inward 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 ascendancy delineate arguments    */   public static void main(String[] args) {      // Creating a Map amongst electoric items too 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 inward ascending order, cost here     ItemToPrice.entrySet().stream()         .sorted(Map.Entry.<String, Integer> comparingByValue())         .forEach(System.out::println);      // now, let's collect the sorted entries inward 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 inward ascending order: "         + sortedByPrice);      // the Map returned past times the previous declaration was non sorted     // because ordering was lost spell collecting number inward Map     // yous demand to utilisation 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 inward increasing order: "         + sortedByValue);      // sorting a Map past times values inward 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 inward 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 inward ascending order:  {Samsung Galaxy=800, HP Laptop=700, Sony Braiva=1000,  Acer HD Monitor=139, Apple iPhone 6S=1200} Map sorted past times value inward increasing order:  {Acer HD Monitor=139, HP Laptop=700, Samsung Galaxy=800,  Sony Braiva=1000, Apple iPhone 6S=1200} Map sorted past times value inward descending order: {Apple iPhone 6S=1200,  Sony Braiva=1000, Samsung Galaxy=800, HP Laptop=700, Acer HD Monitor=139}


You tin give the sack encounter that the map is sorted straightaway past times values, which are integers. In this start example, nosotros receive got printed all entries inward sorted lodge too that's why Acer hard disk drive Monitor comes start because it is to the lowest degree expensive, spell Apple iPhone comes terminal because it is most expensive.

In the minute example, fifty-fifty though nosotros sorted inward the same way every bit before, the terminate number is non what yous receive got expected because nosotros failed to collect the number into a Map which keeps them inward the lodge they were i.e. nosotros should receive got used LinkedHashMap, which keeps entries inward the lodge they were inserted.

In the 3rd too 4th example, nosotros rectified our error too collected the number of the sorted flow into a LinkedHashMap, so nosotros receive got entries inward sorted order. The terminal example, sort entries inward descending order hence, Apple comes start too Acer comes last.

Here is a ane liner inward Java 8 to kind a HashMap past times values:
 but that was using traditional techniques of pre How to kind HashMap past times values inward Java 8 using Lambdas too Stream - Example Tutorial


That's all well-nigh how to kind a Map past times values inward Java 8. yous tin give the sack utilisation this technique to kind whatsoever Map implementations similar HashMap, Hashtable, ConcurrentHashMap, TreeMap etc. If yous don't demand to impress the values or perform whatsoever operation, but yous exactly demand a sorted Map so brand certain yous utilisation collect() method to shop sorted entries into some other Map. Also, when yous utilisation the Collector to collect chemical cistron from sorted Stream, brand certain yous utilisation LinkedHashMap to collect the result, otherwise ordering volition live lost.


Further Reading
Java SE 8 New Features
courses)
  • 5 Books to Learn Java 8 from Scratch (books)
  • How to bring together String inward Java 8 (example)
  • How to utilisation filter() method inward Java 8 (tutorial)
  • Java 8 map + filter + flow instance (tutorial)
  • How to utilisation Stream shape inward Java 8 (tutorial)
  • How to utilisation forEach() method inward Java 8 (example)
  • How to format/parse the appointment amongst LocalDateTime inward Java 8? (tutorial)
  • How to convert List to Map inward Java 8 (solution)
  • 20 Examples of Date too Time inward Java 8 (tutorial)
  • How to utilisation peek() method inward Java 8 (example)
  • How to kind the map past times keys inward Java 8? (example)
  • 10 examples of Options inward Java 8? (example)
  • 5 Free Java 8 and  Java nine courses for Programmers (courses)

  • Thanks for reading this tutorial so far. If yous similar this instance of sorting HashMap inward Java 8 using lambda human face so delight part amongst your friends too colleagues. If yous receive got whatsoever question, feedback, or proposition so delight drib a comment.

    P. S. - If your destination is to larn novel features introduced inward Java 8 so yous tin give the sack likewise cheque out the free Java 8 courses  which exclusively focuses on novel features too naught else.

    No comments:

    Post a Comment