How To Assort A Hashmap Past Times Values Inwards Ascending As Well As Descending Lodge Inwards Coffee Eight - Event Tutorial

In the concluding article, I receive got shown y'all how to sort a Map inwards Java 8 past times keys too today, I'll instruct y'all how to sort a Map past times values using Java 8 features e.g. lambda expression, method reference, streams, too novel methods added into the java.util.Comparator too Map.Entry classes. In fellowship to sort whatever Map e.g. HashMap, Hashtable, LinkedHashMap, TreemMap, or fifty-fifty ConcurrentHashMap, y'all tin commencement acquire ready of entries past times using the entrySet() method too hence y'all 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 y'all got the stream, y'all tin simply telephone telephone the sorted() method which tin sort all Map.Entry objects available inwards Stream using a Comparator.

In fellowship to compare entries of a Map past times values, y'all tin purpose the newly added Map.Entry.comparingByValue() method from the java.util.Map.Entry class.

This is the counterpart of comparingByKey() method which nosotros receive got used inwards the last article. Both of these methods are overloaded to run alongside both Comparable too Comparator objects.

Once y'all sort the stream, y'all tin create whatever y'all desire to create e.g. if y'all simply desire to impress keys, values, or entries inwards sorted order, simply purpose the forEach() method or if y'all desire a Map which is sorted on values hence y'all tin purpose the collect() method of current class.

This method accepts a Collector too allows y'all to capture all elements of Stream into whatever collection y'all desire to. For example, if y'all desire a sorted map hence y'all tin purpose the toMap() method of java.util.stream.Collectors class.


This method is overloaded too provides a duad of choices, for example, y'all tin collect entries inwards whatever sort of map or y'all tin equally good specify the sort of map y'all desire e.g. for kicking the bucket along entries inwards sorted order, we'll purpose the LinkedHashMap. It equally good allows y'all to interruption ties inwards instance of same values e.g. y'all tin conform them inwards the fellowship y'all desire to.

Btw, If y'all are curious, y'all tin equally good come across the Pluralsight's Map.entrySet() method.

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

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

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

7. Provide LinkedHashMap::new to the concluding parameter to forcefulness it to render a LinkedHashMap, to kicking the bucket along the sorted fellowship preserved.

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

This is the novel method added into Comparator course of report 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, too Comparator etc. 

 y'all tin commencement acquire ready of entries past times using the  How to Sort a HashMap past times Values inwards Ascending too Descending Order inwards Java 8 - Example Tutorial

sec Once y'all follow this mensuration y'all volition acquire a Map which is sorted past times values. Now that y'all know the theory too steps, let's come across 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 plan 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 too static methods on interfaces. In this example, I receive got got a Map of the map of items too their expenses e.g. rent, utility, transportation etc.

The Map fundamental is String, which represents detail too value is Integer, which is expenses. Our chore is to sort the Map past times values to detect out which detail damage us most too impress all items inwards their decreasing fellowship 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 alongside string keys too 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 flake past times using method reference     sorted = budget         .entrySet()         .stream()         .sorted(comparingByValue())         .collect(             toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,                 LinkedHashMap::new));      // immediately let's sort the map inwards decreasing fellowship 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 come across that earlier sorting the map has a random fellowship inwards terms of values but first, nosotros receive got sorted them inwards the increasing fellowship of values too afterwards nosotros receive got sorted the same Map inwards the decreasing fellowship of values, that's why rent comes commencement because it damage us highest.

Some tips

1) Use static import to shorten the code, y'all tin static import both Map.Entry too java.util.stream.Collectors classes.

2) Use method reference inwards house of lambda seem wherever y'all can. See this article to acquire to a greater extent than close how to convert lambda seem to method reference inwards Java 8, if y'all are non familiar alongside that.


That's all close how to sort a Map past times values inwards Java 8. You tin come across that it's hence slow to sort the Map using novel methods added to existing classes. All that is possible because of default method characteristic of JDK 8, which allows y'all 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 presently equally y'all 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 purpose filter() method inwards Java 8 (tutorial)
  • How to format/parse the engagement alongside LocalDateTime inwards Java 8? (tutorial)
  • How to purpose Stream course of report inwards Java 8 (tutorial)
  • How to convert List to Map inwards Java 8 (solution)
  • Difference betwixt abstract course of report too interface inwards Java 8? (answer)
  • 20 Examples of Date too Time inwards Java 8 (tutorial)
  • How to purpose 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 hence far. If y'all similar this article hence delight percentage alongside your friends too colleagues. If y'all receive got whatever questions or suggestions hence delight drib a comment.

    Komentar

    Postingan populer dari blog ini

    How To Fix Invalid Target Release: 1.7, 1.8, 1.9, Or 1.10 Fault Inwards Maven Build

    Top Five Books To Larn Agile Too Scrum For Programmers - Best Of Lot, Must Read

    How To Schedule Leap Professional Person Certification Attempt Using Voucher Online - Pace Past Times Pace Guide