Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

Tags: sort stream java
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.


This post first appeared on Javarevisited: Blog About Java Programmin, please read the originial post: here

Share the post

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

×

Subscribe to Javarevisited: Blog About Java Programmin

Get updates delivered right to your inbox!

Thank you for your subscription

×