Kamis, 16 Juli 2020

How to Sort an HashMap by values in Java 8 - Example Tutorial

In the last article, I have shown you how to sort a Map in Java 8 by keys, and today, I'll teach you how to sort a Map by values using Java 8 features e.g. lambda expression, method reference, streams, and new methods added into the java.util.Comparator and Map.Entry classes. In order to sort any Map, like HashMap, Hashtable, LinkedHashMap, TreemMap, or even ConcurrentHashMap, you can first get a set of entries by using the entrySet() method and then you can get the stream by calling the stream() method. The entrySet()  method returns a Set which inherit the stream() method from the java.util.Collection class. Once you got the stream, you can just call the sorted() method which can sort all Map.Entry objects available in Stream using a Comparator.

Lorem ipsum is simply dummy text of the printing and typesetting industry.

Comments


EmoticonEmoticon