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

In the final article, I receive got shown you lot how to sort a Map inwards Java 8 yesteryear keys together with today, I'll learn you lot how to sort a Map yesteryear values using Java 8 features e.g. lambda expression, method reference, streams, together with novel methods added into the java.util.Comparator together with Map.Entry classes. In fellowship to sort whatsoever Map e.g. HashMap, Hashtable, LinkedHashMap, TreemMap, or fifty-fifty ConcurrentHashMap, you lot tin offset acquire prepare of entries yesteryear using the entrySet() method together with and thence you lot tin acquire the current yesteryear 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 merely 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 yesteryear values, you lot tin role 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 travel amongst both Comparable together with Comparator objects.

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

This method accepts a Collector together with 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 together with thence you lot tin role the toMap() method of java.util.stream.Collectors class.


This method is overloaded together with provides a duo of choices, for example, you lot tin collect entries inwards whatsoever sort of map or you lot tin every bit good specify the sort of map you lot desire e.g. for buy the farm along entries inwards sorted order, we'll role the LinkedHashMap. It every bit good allows you lot to suspension ties inwards instance of same values e.g. you lot tin adapt them inwards the fellowship you lot desire to.

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

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

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

5. Collect the consequence using the collect() method.
6. Use Collectors.toMap() method to acquire the consequence inwards roughly other Map. 

7. Provide LinkedHashMap::new to the final parameter to forcefulness it to render a LinkedHashMap, to buy the farm along the sorted fellowship preserved.

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

This is the novel method added into Comparator degree 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, together with Comparator etc. 

 you lot tin offset acquire prepare of entries yesteryear using the  How to Sort a HashMap yesteryear Values inwards Ascending together with Descending Order inwards Java 8 - Example Tutorial

second Once you lot follow this mensuration you lot volition acquire a Map which is sorted yesteryear values. Now that you lot know the theory together with steps, let's encounter the code instance inwards the adjacent department to acquire it right.



Java Program to sort a HashMap yesteryear Values

Here is our consummate Java programme to sort a Map yesteryear values using Java 8 features e.g. novel methods on existing classes inwards Java 8 yesteryear evolving them using default methods together with static methods on interfaces. In this example, I receive got got a Map of the map of items together with their expenses e.g. rent, utility, shipping etc.

The Map fundamental is String, which represents exceptional together with value is Integer, which is expenses. Our describe is to sort the Map yesteryear values to honour out which exceptional terms us most together with 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 yesteryear values inwards Java 8  *   */ public class Main {    public static void main(String[] args) throws Exception {      // a Map amongst string keys together with 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 yesteryear 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 yesteryear values: " + sorted);      // inwards a higher house code tin live cleaned a chip yesteryear using method reference     sorted = budget         .entrySet()         .stream()         .sorted(comparingByValue())         .collect(             toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,                 LinkedHashMap::new));      // straight off 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 yesteryear values inwards descending order: "         + sorted);   }  }  Output map earlier sorting: {grocery=150, utility=130, miscellneous=90, rent=1150,  clothes=120, transportation=100} map after sorting yesteryear values: {miscellneous=90, transportation=100,  clothes=120, utility=130, grocery=150, rent=1150} map after sorting yesteryear 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 fellowship inwards terms of values but first, nosotros receive got sorted them inwards the increasing fellowship of values together with afterwards nosotros receive got sorted the same Map inwards the decreasing fellowship of values, that's why rent comes offset because it terms us highest.

Some tips

1) Use static import to shorten the code, you lot tin static import both Map.Entry together with java.util.stream.Collectors classes.

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


That's all almost how to sort a Map yesteryear 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 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 every bit presently every bit 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 role filter() method inwards Java 8 (tutorial)
  • How to format/parse the appointment amongst LocalDateTime inwards Java 8? (tutorial)
  • How to role Stream degree inwards Java 8 (tutorial)
  • How to convert List to Map inwards Java 8 (solution)
  • Difference betwixt abstract degree together with interface inwards Java 8? (answer)
  • 20 Examples of Date together with Time inwards Java 8 (tutorial)
  • How to role peek() method inwards Java 8 (example)
  • How to sort the map yesteryear keys inwards Java 8? (example)
  • How to sort the may yesteryear 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 together with thence delight portion amongst your friends together with colleagues. If you lot receive got whatsoever questions or suggestions together with thence delight drib a comment.


    Sumber https://javarevisited.blogspot.com/

    0 Response to "How To Form Out A Hashmap Past Times Values Inwards Ascending Together With Descending Guild Inwards Coffee Viii - Illustration Tutorial"

    Post a Comment

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel