How To Form Out A Hashmap Past Times Values Inwards Ascending Together With Descending Guild Inwards Coffee Eight - Event Tutorial

In the final article, I direct maintain shown you lot how to sort a Map inwards Java 8 past times keys as well as today, I'll instruct you lot how to sort a Map past times values using Java 8 features e.g. lambda expression, method reference, streams, as well as novel methods added into the java.util.Comparator as well as Map.Entry classes. In guild to sort whatever Map e.g. HashMap, Hashtable, LinkedHashMap, TreemMap, or fifty-fifty ConcurrentHashMap, you lot tin commencement acquire gear upwards of entries past times using the entrySet() method as well as thence you lot tin acquire the current past times calling the stream() method. The entrySet()  method returns a Set which inherit the stream() method from the java.util.Collection class. Once you lot got the stream, you lot tin but telephone hollo upwards the sorted() method which tin sort all Map.Entry objects available inwards Stream using a Comparator.

In guild to compare entries of a Map past times values, you lot tin utilisation the newly added Map.Entry.comparingByValue() method from the java.util.Map.Entry class.

This is the counterpart of comparingByKey() method which nosotros direct maintain used inwards the last article. Both of these methods are overloaded to piece of occupation amongst both Comparable as well as Comparator objects.

Once you lot sort the stream, you lot tin create whatever you lot desire to create e.g. if you lot but desire to impress keys, values, or entries inwards sorted order, but utilisation the forEach() method or if you lot desire a Map which is sorted on values thence you lot tin utilisation the collect() method of current class.

This method accepts a Collector as well as allows you lot to capture all elements of Stream into whatever collection you lot desire to. For example, if you lot desire a sorted map thence you lot tin utilisation the toMap() method of java.util.stream.Collectors class.



This method is overloaded as well as provides a span of choices, for example, you lot tin collect entries inwards whatever form of map or you lot tin besides specify the form of map you lot desire similar for proceed entries inwards sorted order, we'll utilisation the LinkedHashMap. It besides allows you lot to intermission ties inwards instance of same values e.g. you lot tin conform them inwards the guild you lot desire to.

Btw, If you lot are curious, you lot tin besides encounter the Pluralsight's Map.entrySet() method.

2. Get the current of entries past times calling stream() method.

3. Call the sorted method amongst a Comparator.
4. Use the Map.Entry.comparingByValue() comparator to sort entries past times values.

5. Collect the lawsuit using the collect() method.
6. Use Collectors.toMap() method to acquire the lawsuit inwards to a greater extent than or less other Map. 

7. Provide LinkedHashMap::new to the final parameter to strength it to render a LinkedHashMap, to proceed the sorted guild preserved.

8. In guild to sort inwards decreasing order, but contrary the guild of Comparator using Collections.reverseOrder() or Comparator.reverse() method of Java 8.  

This is the novel method added into Comparator bird inwards Java SE 8. You tin farther see The Complete Java MasterClass for the total listing of novel methods added into fundamental Java classes e.g. Java Collection Framework, String, as well as Comparator, etc. 

 you lot tin commencement acquire gear upwards of entries past times using the  How to Sort a HashMap past times Values inwards Ascending as well as Descending Order inwards Java 8 - Example Tutorial

sec Once you lot follow this measuring you lot volition acquire a Map which is sorted past times values. Now that you lot know the theory as well as steps, let's encounter the code illustration inwards the side past times side department to acquire it right.



Java Program to sort a HashMap past times Values

Here is our consummate Java programme to sort a Map past times values using Java 8 features e.g. novel methods on existing classes inwards Java 8 past times evolving them using default methods as well as static methods on interfaces. In this example, I direct maintain got a Map of the map of items as well as their expenses similar rent, utility, transportation, etc.

The Map fundamental is String, which represents exceptional as well as value is Integer, which is expenses. Our chore is to sort the Map past times values to notice out which exceptional toll us most as well as impress all items inwards their decreasing guild of values.

import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map;  import static java.util.stream.Collectors.*; import static java.util.Map.Entry.*;  /*  * Java Program to sort a Map past times values inwards Java 8  *   */ public class Main {    public static void main(String[] args) throws Exception {      // a Map amongst string keys as well as integer values     Map<String, Integer> budget = new HashMap<>();     budget.put("clothes", 120);     budget.put("grocery", 150);     budget.put("transportation", 100);     budget.put("utility", 130);     budget.put("rent", 1150);     budget.put("miscellneous", 90);      System.out.println("map earlier sorting: " + budget);      // let's sort this map past times values first     Map<String, Integer> sorted = budget         .entrySet()         .stream()         .sorted(comparingByValue())         .collect(             toMap(e -> e.getKey(), e -> e.getValue(), (e1, e2) -> e2,                 LinkedHashMap::new));      System.out.println("map after sorting past times values: " + sorted);      // higher upwards code tin live cleaned a fleck past times using method reference     sorted = budget         .entrySet()         .stream()         .sorted(comparingByValue())         .collect(             toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,                 LinkedHashMap::new));      // right away let's sort the map inwards decreasing guild of value     sorted = budget         .entrySet()         .stream()         .sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))         .collect(             toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,                 LinkedHashMap::new));      System.out.println("map after sorting past times values inwards descending order: "         + sorted);   }  }  Output map earlier sorting: {grocery=150, utility=130, miscellneous=90, rent=1150,  clothes=120, transportation=100} map after sorting past times values: {miscellneous=90, transportation=100,  clothes=120, utility=130, grocery=150, rent=1150} map after sorting past times values in descending order: {rent=1150, grocery=150,  utility=130, clothes=120, transportation=100, miscellneous=90}

You tin encounter that earlier sorting the map has a random guild inwards price of values but first, nosotros direct maintain sorted them inwards the increasing guild of values as well as afterward nosotros direct maintain sorted the same Map inwards the decreasing guild of values, that's why rent comes commencement because it toll us highest.

Some tips

1) Use static import to shorten the code, when you lot utilisation the static import characteristic to import both Map.Entry as well as java.util.stream.Collectors classes you lot tin refer their methods without including bird cite similar instead of Collectors.toMap() you lot tin but utilisation toMap().

2) Use method reference inwards house of lambda seem wherever you lot can. See this article to larn to a greater extent than virtually how to convert lambda seem to method reference inwards Java 8, if you lot are non familiar amongst that.


That's all virtually how to sort a Map past times values inwards Java 8. You tin encounter that it's thence slow to sort the Map using novel methods added to existing classes. All that is possible because of the default method characteristic of JDK 8, which allows you lot to add together novel methods to existing classes.

Before this enhancement, it wasn't possible inwards Java without breaking the existing customer of interfaces because equally shortly equally you lot add together a novel method to an interface, all its clients had to implement it.

This is non required anymore if the method is default or static because they are non abstract but concrete methods.


Further Learning
The Complete Java MasterClass
books)
  • What is the default method inwards Java 8? (example)
  • How to bring together String inwards Java 8 (example)
  • How to utilisation filter() method inwards Java 8 (tutorial)
  • How to format/parse the appointment amongst LocalDateTime inwards Java 8? (tutorial)
  • How to utilisation Stream bird inwards Java 8 (tutorial)
  • How to convert List to Map inwards Java 8 (solution)
  • Difference betwixt abstract bird as well as interface inwards Java 8? (answer)
  • 20 Examples of Date as well as Time inwards Java 8 (tutorial)
  • How to utilisation peek() method inwards Java 8 (example)
  • How to sort the map past times keys inwards Java 8? (example)
  • How to sort the may past times values inwards Java 8? (example)
  • 10 examples of Options inwards Java 8? (example)

  • Thanks for reading this article thence far. If you lot similar this article thence delight portion amongst your friends as well as colleagues. If you lot direct maintain whatever questions or suggestions thence delight drib a comment.

    P.S.: If you lot but desire to larn to a greater extent than virtually novel features inwards Java 8 thence delight encounter the What's New inwards Java 8 online course of educational activity on Pluralsight. It explains all the of import features of Java 8 similar lambda expressions, streams, functional interfaces, Optional, novel Date Time API as well as other miscellaneous changes.

    Belum ada Komentar untuk "How To Form Out A Hashmap Past Times Values Inwards Ascending Together With Descending Guild Inwards Coffee Eight - Event Tutorial"

    Posting Komentar

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel