Sort HashMap by Value or Key in Java

Learn How to sort a Map in Java using plain Java, Java Streams API, and Guava Library.

Overview

Java HashMap is an unsorted and unordered collection. However, it is one of the most popular and most used collections in Java. In this tutorial we’ll focus on the ways to sort HashMap elements by the value or by the key.

We’ll first prepare a HashMap of custom objects as values and then explore the ways to sort it using TreeMap, Java Streams, TreeSet, or ArrayList.

Prepare a HashMap

We will first create a HashMap and use it throughout the tutorial. Our map stores Product Ids as a keys and Product objects as values.

Map<Long, Product> map;
Code language: Java (java)

In order to be able to sort the map based on the value (Product), we will need our Product to implement Comparable interface. Thus, our Product class looks like this.

public class Product implements Comparable<Product> { private Long id; private String name; public int compareTo(Product product) { return this.name.compareTo(product.name); } // Constructors, Getters and Setters }
Code language: Java (java)

Now, let’s create a few instances of Product and put them in our map.

Product product1 = new Product(2L, "Television"); Product product2 = new Product(4L, "Grinder"); Product product3 = new Product(3L, "Headphone"); Product product4 = new Product(5L, "Monitor"); map = new HashMap<>(); map.put(product1.getId(), product1); map.put(product2.getId(), product2); map.put(product3.getId(), product3); map.put(product4.getId(), product4);
Code language: Java (java)

Sorting HashMap by Key

In this section, we will cover different ways of sorting a HashMap using its key.

Sort Map with TreeMap

This is the simplest way of sorting a HashMap. Java TreeMap elements are always sorted based on the key.
Thus, we can simply create a TreeMap instance by providing our map as constructor argument.

Map<Long, Product> treeMap = new TreeMap<>(map);
Code language: Java (java)

This creates a TreeMap instance containing all the elements from our map.

2=Product(id=2, name=Television)
3=Product(id=3, name=Headphone)
4=Product(id=4, name=Grinder)
5=Product(id=5, name=Monitor)

Printing the tree map we can see all of the elements are sorted based on the key.

Alternatively, we can also use TreeMap#putAll() method to add all elements from our map into the tree map instance.

Map<Long, Product> treeMap = new TreeMap<>(); treeMap.putAll(map);
Code language: Java (java)

This produces the same result as the previous one.

Using Java Streams API

Alternatively, Java Streams API provides a way to sort the Map elements. This is done by using an Intermediate Stream operation of sorted().

map.entrySet() .stream() .sorted(Map.Entry.comparingByKey()) .forEach(System.out::println);
Code language: Java (java)

The Map.Entry#comparingByKey() provides a Comparator that is used to sort the Map elements over the key. The output of the snippet shows that the map is correctly sorted.

2=Product(id=2, name=Television)
3=Product(id=3, name=Headphone)
4=Product(id=4, name=Grinder)
5=Product(id=5, name=Monitor)

Using TreeSet

As we know, Java TreeSet are by default sorted. That is why we can use TreeSet to sort the keys from our map.

Set<Long> keys = new TreeSet<>(map.keySet());
Code language: Java (java)

As expected, the keys in the output are sorted.

[2, 3, 4, 5]

Using ArrayList

Similar to TreeSet, we can use ArrayList to sort HashMap by key.

List<Long> keys = new ArrayList<>(map.keySet()); Collections.sort(keys);
Code language: Java (java)

We are creating a new ArrayList using all the keys from the map. However, List interface in Java is not a sorted collection. Thus, we will use utility method provided by Collections#sort() to sort the list.

[2, 3, 4, 5]

Output shows, all the keys from the HashMap are sorted.

Sorting HashMap by Value

So far we sorted our HashMap based on the keys. Now, we will look at different ways to sort HashMap by values. The value type of our map is a custom object. That means, to perform on the sorting based on the value, we must provide a Comparator or the custom object must be Comparable.

This is why, our Product implements Comparable and compares based on the name of the product.

Using Java Streams API

This time we will use Java Streams to sort a HashMap by value. To do so, we will use sorted() method of the streams.

map.entrySet() .stream() .sorted(Map.Entry.comparingByValue()) .forEach(System.out::println);
Code language: Java (java)

As shown in the snippet, the sorting is done by the Comparator instance provided by Map.Entry#comparingByValue().

4=Product(id=4, name=Grinder)
3=Product(id=3, name=Headphone)
5=Product(id=5, name=Monitor)
2=Product(id=2, name=Television)

And our, map is now sorted based on the name of the product.

Using TreeSet

Similar to using TreeSet constructor for sorting Map keys, we can use TreeSet constructor to sort map values.

Set<Product> values = new TreeSet<>(map.values());
Code language: Java (java)

We are using Map#values() that returns a Collection of all the values from the map.

Product(id=4, name=Grinder)
Product(id=3, name=Headphone)
Product(id=5, name=Monitor)
Product(id=2, name=Television)

Using ArrayList

Let’s use ArrayList constructor to create a list of all the values from the map.

List<Product> products = new ArrayList<>(map.values()); Collections.sort(products);
Code language: Java (java)

As the ArrayList implementation doesn’t support sorting by default, we are sorting the list using Collections#sort() method.

Product(id=4, name=Grinder)
Product(id=3, name=Headphone)
Product(id=5, name=Monitor)
Product(id=2, name=Television)

The output shows, the map is now sorted by the name of the product instances.

Summary

We covered various ways to Sort a HashMap by value or by key using plain Java and Java Streams.

We also understood that, when we have custom objects as keys or as values, we need to provide their sorting strategy. This is done by either providing a Comparator implementation or the custom object must implement Comparable. In this tutorial, we used TreeMap, Java Streams API, TreeSet, and ArrayList to sort the map keys and values.

For full source of the examples used here, please visit our Github Repository.