How To Kind Out A Map Yesteryear Keys Inwards Coffee Eight - Illustration Tutorial

In the final article, I receive got shown y'all how to sort a Map yesteryear values inwards Java 8 too inwards this tutorial, y'all volition larn how to sort a Map yesteryear keys e.g. an HashMap, ConcurrentHashMap, LinkedHashmap, or fifty-fifty Hashtable. Theoretically, y'all cannot sort a Map because it doesn't supply whatever ordering guarantee. For example, when y'all iterate over a HashMap, y'all don't know inwards which lodge entries volition live traversed because HashMap doesn't supply whatever ordering. Then, how tin y'all sort a Map which doesn't back upwards order? Well, y'all can't too that's why y'all entirely sort entries of HashMap but y'all don't store the consequence dorsum into HasMap or whatever other Map which doesn't back upwards ordering. If y'all produce so, so sorting volition live lost.

Here is an event of wrong sorting. Here fifty-fifty after sorting the Map, nosotros are doing the fault of storing the consequence dorsum into a Map which doesn't supply whatever ordering guarantee, therefore the consequence is an unordered map fifty-fifty after sorting.

Map sorted = budget .entrySet() .stream() .sorted(comparingByKey()) .collect(toMap(e -> e.getKey(), e -> e.getValue(), (e1, e2) -> e2));

Here is the output to confirm what I said:
map before sorting: {grocery=150, utility=130, miscellneous=90,  rent=1150, clothes=120, transportation=100} map after sorting yesteryear keys: {grocery=150, utility=130, miscellneous=90,  rent=1150, clothes=120, transportation=100}

If Map was sorted so the "clothes" should receive got come upwards outset ahead of "grocery". The fault was blindly relying on toMap() method of Collectors class. This shape provides no guarantee of what sort of Map volition live used to collect those elements. Since Map interface doesn't guarantee order, they are too non saltation to store chemical portion inwards whatever order.

Though, it's slow to solve this work because Collectors shape too supply an overloaded version of toMap() shape which allows y'all to instruct which sort of Map should live used to store those entries. You tin usage a LinkedHashMap to store mappings to save the sorting lodge because LinkedHashMap give-up the ghost along keys inwards the lodge they were added. Here is the modified code which sorts a Map inwards the lodge of keys:

Map sorted = budget .entrySet() .stream() .sorted(comparingByKey()) .collect(toMap(e -> e.getKey(), e -> e.getValue(), (e1, e2) -> e2), LinkedHashMap::new));

The code passed into to toMap() method is interesting, the outset parameter is used every bit a key, minute is used every bit value too 3rd is used to pause ties i.e. if ii entries are equal so which entries volition live chosen is decided yesteryear the 3rd parameter, hither nosotros are using the minute entry. The quaternary parameter is the of import one, which uses a constructor reference to say Collector that for copying a LinkedHashMap should live used.  See Java SE 8 for the Really Impatient to larn to a greater extent than virtually how constructor interference is used.



Steps to sort a Map yesteryear keys inwards Java 8

Here are the high-level steps y'all tin convey to sort a Map e.g. HashMap, Hashtable, ConcurentHashMap or LinkedHashMap to sort them inwards the ascending too descending lodge of their keys:

1) Get all entries yesteryear calling the Map.entrySet() method

2) Get a flow of entries yesteryear calling the stream() method, which Set inherit from Collection interface.

3) Sort all entries of Stream yesteryear calling the sorted() method.

4) In lodge to sort them yesteryear keys, supply a Comparator to a sorted() method which sorts entries yesteryear keys. This tin live done yesteryear calling Map.Entry.comparingKey() method returns a Comparator which compares cardinal inwards their natural order.

5) Store the consequence of sorting inwards a LinkedHashMap yesteryear using the collect() method of Stream class.

6) Use Collectors.toMap() method to collect sorted entries into LinkedHashMap




Java Program to sort a Map yesteryear keys inwards JDK 8

Here is the consummate Java plan to sort Map e.g. HashMap yesteryear keys inwards JDK 8. In this example, y'all volition larn to sort Map yesteryear both lambda aspect too method reference. We'll too usage novel classes e.g. Stream too novel methods added into Map.Entry shape to sort all entries yesteryear their Map too store the consequence into a LinkedHashMap.

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 keys inwards Java 8 *  */ public class Java8Demo{  public static void main(String[] args) throws Exception {  // a Map amongst 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 before sorting: " + budget);  // let's sort this map yesteryear keys first Map<String, Integer> sorted = budget .entrySet() .stream() .sorted(comparingByKey()) .collect( toMap(e -> e.getKey(), e -> e.getValue(), (e1, e2) -> e2, LinkedHashMap::new));  System.out.println("map after sorting yesteryear keys: " + sorted);  // higher upwards code tin live cleaned a flake yesteryear using method reference sorted = budget .entrySet() .stream() .sorted(comparingByKey()) .collect( toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));   // straightaway let's sort the map inwards decreasing lodge of keys sorted = budget .entrySet() .stream() .sorted(Collections.reverseOrder(Map.Entry.comparingByKey())) .collect( toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));  System.out.println("map after sorting yesteryear keys inwards descending order: " + sorted); }  }  Output map before sorting: {grocery=150, utility=130, miscellneous=90,         rent=1150, clothes=120, transportation=100} map after sorting yesteryear keys: {clothes=120, grocery=150, miscellneous=90,         rent=1150, transportation=100, utility=130} map after sorting yesteryear keys inwards descending order: {utility=130,         transportation=100, rent=1150, miscellneous=90, grocery=150, clothes=120}


You tin encounter that initially map was non sorted but it is after sorted inwards the lodge of keys, which are a string too that's why wearing clothing come upwards ahead of grocery. Similarly, when nosotros sorted the map inwards the descending order, wearing clothing come upwards last. This proves that our sorting code is working fine.


If y'all desire to a greater extent than sophistication too customization y'all tin produce that at Comparator marking too y'all tin supply additional Comparator to comparingKey() method, which yesteryear default compare keys inwards their natural order.

For example, if a cardinal were non String but a user object e.g. a Book, so y'all could receive got sorted mass yesteryear title, writer or toll yesteryear providing the corresponding comparator to comparingKey() method of java.util.Map.Entry class. Both comparingKey() too comparingValue() are overloaded to convey a Comparator. You tin encounter a practiced Java 8 mass e.g. Java SE 8 for Really Impatient to larn to a greater extent than virtually them.

 y'all volition larn how to sort a Map yesteryear keys e How to sort a Map yesteryear keys inwards Java 8 - Example Tutorial


That's all virtually how to sort a Map yesteryear keys inwards Java 8. The simplest agency to arrive at this is yesteryear using the sorted() method of Stream too the newly added comparingKey() method of Map.Entry class. The flow sorts all elements too so depending upon your need, y'all tin either impress entries inwards sorted lodge or stored them inwards an ordered map e.g. LinkedHashMap or a sorted map e.g. TreeMap. You tin too sort entries inwards their opposite lodge yesteryear only reversing the Comparator using the Collections.reverseOrder() method or Comparator.reversed() method of Java 8.


Further Learning
The Complete Java MasterClass
Java SE 8 Developer BootCamp
Refactoring to Java 8 Streams too Lambdas Self- Study Workshop

Related Java 8 Tutorials
If y'all are interested inwards learning to a greater extent than virtually novel features of Java 8, hither are my before articles roofing to a greater extent than or less of the of import concepts of Java 8:

  • 20 Examples of Date too Time inwards Java 8 (tutorial)
  • How to usage Stream shape inwards Java 8 (tutorial)
  • How to usage filter() method inwards Java 8 (tutorial)
  • How to usage forEach() method inwards Java 8 (example)
  • How to bring together String inwards Java 8 (example)
  • How to convert List to Map inwards Java 8 (solution)
  • How to usage peek() method inwards Java 8 (example)
  • 5 Books to Learn Java 8 from Scratch (books)
Thank for reading this article so far. If y'all similar this tutorial so delight portion amongst your friends too colleagues. If y'all receive got whatever inquiry or feedback so delight drib a comment.

P.S. : If y'all desire to larn to a greater extent than virtually novel features inwards Java 8 so delight encounter the tutorial What's New inwards Java 8. It explains virtually all of import features of Java 8 e.g. lambda expressions, streams, functional inteface, Optionals, novel engagement too fourth dimension API too other miscelleneous changes.

Sumber https://javarevisited.blogspot.com/

0 Response to "How To Kind Out A Map Yesteryear Keys Inwards Coffee Eight - Illustration Tutorial"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel