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 Java’s most popular and most used collections. 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 keys and Product objects as values.

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

To sort the Map based on the value (Product), we will need our Product to implement the 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 Product instances and put them on 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 a HashMap by Key

This section will cover different ways of sorting a HashMap using its key.

Sort Map with TreeMap

Java TreeMap implements the Map interface and stores elements sorted by their keys. We can use TreeMap to sort a Java HashMap instance.

Map<Long, Product> treeMap = new TreeMap<>(map);
treeMap.entrySet().forEach(System.out::println);

//prints:
//2=Product(id=2, name=Television)
//3=Product(id=3, name=Headphone)
//4=Product(id=4, name=Grinder)
//5=Product(id=5, name=Monitor)Code language: Java (java)

The TreeMap constructor creates a new TreeMap instance containing all the entries from the given Map.

Using Java Streams sorted() Method

The sorted() method, an intermediate operation of the Java Stream, returns a new Stream containing all the Stream elements sorted by the given Comparator. We can use Java Stream’s sorted() method to sort a HashMap.

map.entrySet().stream()
  .sorted(Map.Entry.comparingByKey())
  .forEach(System.out::println);
//prints:
//2=Product(id=2, name=Television)
//3=Product(id=3, name=Headphone)
//4=Product(id=4, name=Grinder)
//5=Product(id=5, name=Monitor)Code language: Java (java)

Please take note of the argument to the sorted() method. The Entry class provides a Comparator to sort a HashMap using the key.

Using a TreeSet

Java TreeSet is an implementation of Set that stores sorted elements. We can use a TreeSet instance to sort Java HashMap keys.

Set<Long> keys = new TreeSet<>(map.keySet());
System.out.println(keys);

//prints:
//[2, 3, 4, 5]Code language: Java (java)

Using an ArrayList

Alternatively, the sort() method of Java Collections class sorts all the elements in a List. We can use an ArrayList to sort Java HashMap keys.

List<Long> keys = new ArrayList<>(map.keySet());
Collections.sort(keys);
System.out.println(keys);

//prints:
//[2, 3, 4, 5]Code language: Java (java)

The ArrayList constructor creates a new ArrayList instance containing all the elements from the given collection. In this example, we used a Set of our HashMap keys.

Sorting a HashMap by Value

So far, we have 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. To perform the sorting based on the value, we must provide a Comparator, or the custom object must be Comparable.
Our Product implements Comparable and compares based on the Product’s name.

Using Java Streams sorted() Method

This time we will use the Java Streams sorted() method to sort a HashMap by values.

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

//prints:
//4=Product(id=4, name=Grinder)
//3=Product(id=3, name=Headphone)
//5=Product(id=5, name=Monitor)
//2=Product(id=2, name=Television)Code language: Java (java)

Please note that we used the Map.Entry.comparingByValue() Comparator that sorts a Map based on the values.

Using TreeSet

Like using the TreeSet constructor for sorting Map keys, we can use the TreeSet constructor to sort HashMap by values.

Set<Product> values = new TreeSet<>(map.values());
values.forEach(System.out::println);

//prints:
//Product(id=4, name=Grinder)
//Product(id=3, name=Headphone)
//Product(id=5, name=Monitor)
//Product(id=2, name=Television)Code language: Java (java)

Using ArrayList

To use an ArrayList to sort Java HashMap values, we need to prepare an ArrayList containing all the Map values and then use the sort() method of the Collections class.

List<Product> products = new ArrayList<>(map.values());
Collections.sort(products);

products.forEach(System.out::println);
//prints:
//Product(id=4, name=Grinder)
//Product(id=3, name=Headphone)
//Product(id=5, name=Monitor)
//Product(id=2, name=Television)Code language: Java (java)

Summary

The article demonstrated several ways of Sorting a Java HashMap by keys or values.

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

For the complete source code of the examples used here, please visit our GitHub Repository.