In the concluding article, I direct maintain shown you lot how to sort a Map past times values inwards Java 8 as well as inwards this tutorial, you lot volition acquire how to sort a Map past times keys e.g. an HashMap, ConcurrentHashMap, LinkedHashmap, or fifty-fifty Hashtable. Theoretically, you lot cannot sort a Map because it doesn't render whatever ordering guarantee. For example, when you lot iterate over a HashMap, you lot don't know inwards which fellowship entries volition live traversed because HashMap doesn't render whatever ordering. Then, how tin you lot sort a Map which doesn't back upwards order? Well, you lot can't as well as that's why you lot solely sort entries of HashMap but you lot don't store the trial dorsum into HasMap or whatever other Map which doesn't back upwards ordering. If you lot create so, as well as so sorting volition live lost.
Here is an instance of wrong sorting. Here fifty-fifty after sorting the Map, nosotros are doing the error of storing the trial dorsum into a Map which doesn't render whatever ordering guarantee, thence the trial is an unordered map fifty-fifty after sorting.
Here is the output to confirm what I said:
If Map was sorted as well as so the "clothes" should direct maintain come upwards get-go ahead of "grocery". The error was blindly relying on toMap() method of Collectors class. This shape provides no guarantee of what form of Map volition live used to collect those elements. Since Map interface doesn't guarantee order, they are likewise non leap to store chemical cistron inwards whatever order.
Though, it's tardily to solve this occupation because Collectors shape likewise render an overloaded version of toMap() shape which allows you lot to instruct which form of Map should live used to store those entries. You tin utilisation a LinkedHashMap to store mappings to save the sorting fellowship because LinkedHashMap give-up the ghost along keys inwards the fellowship they were added. Here is the modified code which sorts a Map inwards the fellowship of keys:
The code passed into to toMap() method is interesting, the get-go parameter is used every bit a key, 2nd is used every bit value as well as 3rd is used to interruption ties i.e. if 2 entries are equal as well as so which entries volition live chosen is decided past times the 3rd parameter, hither nosotros are using the 2nd entry. The 4th 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 acquire to a greater extent than close how constructor interference is used.
1) Get all entries past times calling the Map.entrySet() method
2) Get a flow of entries past times calling the stream() method, which Set inherit from Collection interface.
3) Sort all entries of Stream past times calling the sorted() method.
4) In fellowship to sort them past times keys, render a Comparator to a sorted() method which sorts entries past times keys. This tin live done past times calling Map.Entry.comparingKey() method returns a Comparator which compares substitution inwards their natural order.
5) Store the trial of sorting inwards a LinkedHashMap past times using the collect() method of Stream class.
6) Use Collectors.toMap() method to collect sorted entries into LinkedHashMap
You tin come across that initially map was non sorted but it is subsequently sorted inwards the fellowship of keys, which are a string as well as that's why clothe come upwards ahead of grocery. Similarly, when nosotros sorted the map inwards the descending order, clothe come upwards last. This proves that our sorting code is working fine.
If you lot desire to a greater extent than sophistication as well as customization you lot tin create that at Comparator marker as well as you lot tin render additional Comparator to comparingKey() method, which past times default compare keys inwards their natural order.
For example, if a substitution were non String but a user object e.g. a Book, as well as so you lot could direct maintain sorted mass past times title, writer or cost past times providing the corresponding comparator to comparingKey() method of java.util.Map.Entry class. Both comparingKey() as well as comparingValue() are overloaded to bring a Comparator. You tin come across a practiced Java 8 mass e.g. Java SE 8 for Really Impatient to acquire to a greater extent than close them.
That's all close how to sort a Map past times keys inwards Java 8. The simplest agency to hit this is past times using the sorted() method of Stream as well as the newly added comparingKey() method of Map.Entry class. The flow sorts all elements as well as and so depending upon your need, you lot tin either impress entries inwards sorted fellowship or stored them inwards an ordered map e.g. LinkedHashMap or a sorted map e.g. TreeMap. You tin likewise sort entries inwards their contrary fellowship past times simply 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 as well as Lambdas Self- Study Workshop
Related Java 8 Tutorials
If you lot are interested inwards learning to a greater extent than close novel features of Java 8, hither are my before articles roofing roughly of the of import concepts of Java 8:
Here is an instance of wrong sorting. Here fifty-fifty after sorting the Map, nosotros are doing the error of storing the trial dorsum into a Map which doesn't render whatever ordering guarantee, thence the trial is an unordered map fifty-fifty after sorting.
Mapsorted = 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 past times keys: {grocery=150, utility=130, miscellneous=90, rent=1150, clothes=120, transportation=100}
If Map was sorted as well as so the "clothes" should direct maintain come upwards get-go ahead of "grocery". The error was blindly relying on toMap() method of Collectors class. This shape provides no guarantee of what form of Map volition live used to collect those elements. Since Map interface doesn't guarantee order, they are likewise non leap to store chemical cistron inwards whatever order.
Though, it's tardily to solve this occupation because Collectors shape likewise render an overloaded version of toMap() shape which allows you lot to instruct which form of Map should live used to store those entries. You tin utilisation a LinkedHashMap to store mappings to save the sorting fellowship because LinkedHashMap give-up the ghost along keys inwards the fellowship they were added. Here is the modified code which sorts a Map inwards the fellowship of keys:
Mapsorted = 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 get-go parameter is used every bit a key, 2nd is used every bit value as well as 3rd is used to interruption ties i.e. if 2 entries are equal as well as so which entries volition live chosen is decided past times the 3rd parameter, hither nosotros are using the 2nd entry. The 4th 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 acquire to a greater extent than close how constructor interference is used.
Steps to sort a Map past times keys inwards Java 8
Here are the high-level steps you lot tin bring to sort a Map e.g. HashMap, Hashtable, ConcurentHashMap or LinkedHashMap to sort them inwards the ascending as well as descending fellowship of their keys:1) Get all entries past times calling the Map.entrySet() method
2) Get a flow of entries past times calling the stream() method, which Set inherit from Collection interface.
3) Sort all entries of Stream past times calling the sorted() method.
4) In fellowship to sort them past times keys, render a Comparator to a sorted() method which sorts entries past times keys. This tin live done past times calling Map.Entry.comparingKey() method returns a Comparator which compares substitution inwards their natural order.
5) Store the trial of sorting inwards a LinkedHashMap past times using the collect() method of Stream class.
6) Use Collectors.toMap() method to collect sorted entries into LinkedHashMap
Java Program to sort a Map past times keys inwards JDK 8
Here is the consummate Java plan to sort Map e.g. HashMap past times keys inwards JDK 8. In this example, you lot volition acquire to sort Map past times both lambda human face as well as method reference. We'll likewise utilisation novel classes e.g. Stream as well as novel methods added into Map.Entry shape to sort all entries past times their Map as well as store the trial 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 past times keys inwards Java 8 * */ public class Java8Demo{ 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 before sorting: " + budget); // let's sort this map past times 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 past times keys: " + sorted); // higher upwards code tin live cleaned a fleck past times using method reference sorted = budget .entrySet() .stream() .sorted(comparingByKey()) .collect( toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new)); // right away let's sort the map inwards decreasing fellowship 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 past times keys inwards descending order: " + sorted); } } Output map before sorting: {grocery=150, utility=130, miscellneous=90, rent=1150, clothes=120, transportation=100} map after sorting past times keys: {clothes=120, grocery=150, miscellneous=90, rent=1150, transportation=100, utility=130} map after sorting past times keys inwards descending order: {utility=130, transportation=100, rent=1150, miscellneous=90, grocery=150, clothes=120}
You tin come across that initially map was non sorted but it is subsequently sorted inwards the fellowship of keys, which are a string as well as that's why clothe come upwards ahead of grocery. Similarly, when nosotros sorted the map inwards the descending order, clothe come upwards last. This proves that our sorting code is working fine.
If you lot desire to a greater extent than sophistication as well as customization you lot tin create that at Comparator marker as well as you lot tin render additional Comparator to comparingKey() method, which past times default compare keys inwards their natural order.
For example, if a substitution were non String but a user object e.g. a Book, as well as so you lot could direct maintain sorted mass past times title, writer or cost past times providing the corresponding comparator to comparingKey() method of java.util.Map.Entry class. Both comparingKey() as well as comparingValue() are overloaded to bring a Comparator. You tin come across a practiced Java 8 mass e.g. Java SE 8 for Really Impatient to acquire to a greater extent than close them.
That's all close how to sort a Map past times keys inwards Java 8. The simplest agency to hit this is past times using the sorted() method of Stream as well as the newly added comparingKey() method of Map.Entry class. The flow sorts all elements as well as and so depending upon your need, you lot tin either impress entries inwards sorted fellowship or stored them inwards an ordered map e.g. LinkedHashMap or a sorted map e.g. TreeMap. You tin likewise sort entries inwards their contrary fellowship past times simply 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 as well as Lambdas Self- Study Workshop
Related Java 8 Tutorials
If you lot are interested inwards learning to a greater extent than close novel features of Java 8, hither are my before articles roofing roughly of the of import concepts of Java 8:
- 20 Examples of Date as well as Time inwards Java 8 (tutorial)
- How to utilisation Stream shape inwards Java 8 (tutorial)
- How to utilisation filter() method inwards Java 8 (tutorial)
- How to utilisation 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 utilisation peek() method inwards Java 8 (example)
- 5 Books to Learn Java 8 from Scratch (books)
P.S. : If you lot desire to acquire to a greater extent than close novel features inwards Java 8 as well as so delight come across the tutorial What's New inwards Java 8. It explains close all of import features of Java 8 e.g. lambda expressions, streams, functional inteface, Optionals, novel appointment as well as fourth dimension API as well as other miscelleneous changes.