Sorting a HashMap

JavaJavaBeginner
Practice Now

Introduction

A HashMap is a collection that stores key-value pairs. However, it does not store the key-value pairs in any particular order, and it does not maintain the insertion order of elements. There may be cases when we want to view the data stored in a sorted manner. In such cases, we need to sort the HashMap.

Create a new Java file

First, we need to create a new Java file to write the code for sorting a HashMap. Open the terminal and navigate to the directory where you want to create the file. Use the following command to create a new file named HashMapSortDemo.java.

touch HashMapSortDemo.java

Sorting by Keys using Collections.sort()

We can sort a HashMap by keys using the Collections.sort() method. Follow the code below:

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;

public class HashMapSortDemo {
    public static void main(String args[]) {
        HashMap<String, Integer> unsortedMap = new HashMap<>();
        unsortedMap.put("one", 1);
        unsortedMap.put("two", 2);
        unsortedMap.put("three", 3);
        unsortedMap.put("four", 4);
        unsortedMap.put("five", 5);

        System.out.println("Printing the Unsorted HashMap");
        for(Entry<String, Integer> e : unsortedMap.entrySet()) {
            System.out.println(e.getKey() + "-->" + e.getValue());
        }

        ArrayList<String> sortedList = new ArrayList<>(unsortedMap.keySet());
        Collections.sort(sortedList);

        System.out.println("\nPrinting the Alphabetically Sorted Keys");
        for(String s : sortedList) {
            System.out.println(s + "-->" + unsortedMap.get(s));
        }
    }
}

The code above is sorting the HashMap by keys using the Collections.sort() method.

Use the following command to compile and run the code:

javac HashMapSortDemo.java && java HashMapSortDemo

Sorting by Values using Collections.sort()

We can sort a HashMap by values using the Collections.sort() method. Follow the code below:

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map.Entry;

public class HashMapSortDemo {
    public static void main(String args[]) {
        HashMap<String, Integer> unsortedMap = new HashMap<>();
        unsortedMap.put("one", 1);
        unsortedMap.put("two", 2);
        unsortedMap.put("three", 3);
        unsortedMap.put("four", 4);
        unsortedMap.put("five", 5);

        System.out.println("Printing the Unsorted HashMap");
        for(Entry<String, Integer> e : unsortedMap.entrySet()) {
            System.out.println(e.getKey() + "-->" + e.getValue());
        }

        ArrayList<Integer> sortedList = new ArrayList<>(unsortedMap.values());
        Collections.sort(sortedList);

        System.out.println("\nPrinting the Sorted Values");
        for(Integer i : sortedList) {
            System.out.println(i);
        }
    }
}

The code above is sorting the HashMap by values using the Collections.sort() method.

Use the following command to compile and run the code:

javac HashMapSortDemo.java && java HashMapSortDemo

Sorting by Keys using TreeMap

We can sort a HashMap by keys using a TreeMap. A TreeMap automatically stores the key-value pairs in sorted order(sorted by keys). Follow the code below:

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.TreeMap;

public class HashMapSortDemo {
    public static void main(String args[]) {
        HashMap<String, Integer> unsortedMap = new HashMap<>();
        unsortedMap.put("one", 1);
        unsortedMap.put("two", 2);
        unsortedMap.put("three", 3);
        unsortedMap.put("four", 4);
        unsortedMap.put("five", 5);

        System.out.println("Printing the Unsorted HashMap");
        for(Entry<String, Integer> e : unsortedMap.entrySet()) {
            System.out.println(e.getKey() + "-->" + e.getValue());
        }

        TreeMap<String, Integer> sortedMap = new TreeMap<>(unsortedMap);

        System.out.println("\nPrinting the Sorted TreeMap");
        for(Entry<String, Integer> e : sortedMap.entrySet()) {
            System.out.println(e.getKey() + "-->" + e.getValue());
        }
    }
}

The code above is sorting the HashMap by keys using a TreeMap.

Use the following command to compile and run the code:

javac HashMapSortDemo.java && java HashMapSortDemo

Sorting by Values using TreeSet

We can sort a HashMap by values using a TreeSet. A TreeSet also stores data in sorted order(sorted by values). Follow the code below:

import java.util.HashMap;
import java.util.Map.Entry;
import java.util.TreeSet;

public class HashMapSortDemo {
    public static void main(String args[]) {
        HashMap<String, Integer> unsortedMap = new HashMap<>();
        unsortedMap.put("one", 1);
        unsortedMap.put("two", 2);
        unsortedMap.put("three", 3);
        unsortedMap.put("four", 4);
        unsortedMap.put("five", 5);

        unsortedMap.put("fourteen", 4);
        unsortedMap.put("fifteen", 5);
        unsortedMap.put("twenty", 2);

        System.out.println("Printing the Unsorted HashMap");
        for(Entry<String, Integer> e : unsortedMap.entrySet()) {
            System.out.println(e.getKey() + "-->" + e.getValue());
        }

        TreeSet<Integer> sortedSet = new TreeSet<>(unsortedMap.values());

        System.out.println("\nThe sorted values are: " + sortedSet);
    }
}

The code above is sorting the HashMap by values using a TreeSet.

Use the following command to compile and run the code:

javac HashMapSortDemo.java && java HashMapSortDemo

Sorting using Stream and Lambda expressions

We can sort a HashMap in a single line of code by using Java Streams and the Lambda expressions. Follow the code below:

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Stream;

public class HashMapSortDemo {
    public static void main(String args[]) {
        HashMap<String, Integer> unsortedMap = new HashMap<>();
        unsortedMap.put("one", 1);
        unsortedMap.put("two", 2);
        unsortedMap.put("three", 3);
        unsortedMap.put("four", 4);
        unsortedMap.put("five", 5);

        System.out.println("Printing the Unsorted HashMap");
        for(Entry<String, Integer> e : unsortedMap.entrySet()) {
            System.out.println(e.getKey() + "-->" + e.getValue());
        }

        Stream<Entry<String, Integer>> sortedStream = unsortedMap.entrySet()
                                        .stream()
                                        .sorted(Map.Entry.<String, Integer>comparingByKey());

        System.out.println("\nPrinting the Sorted Key-Value Pairs");
        sortedStream.forEach(System.out :: println);
    }
}

The code above is sorting the HashMap using Java Streams and Lambda expressions.

Use the following command to compile and run the code:

javac HashMapSortDemo.java && java HashMapSortDemo

Sorting by Values using Stream and Lambda expressions

We can also sort a HashMap by values using Java Streams and Lambda expressions. Follow the code below:

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Stream;

public class HashMapSortDemo {
    public static void main(String args[]) {
        HashMap<String, Integer> unsortedMap = new HashMap<>();
        unsortedMap.put("one", 1);
        unsortedMap.put("two", 2);
        unsortedMap.put("three", 3);
        unsortedMap.put("four", 4);
        unsortedMap.put("five", 5);

        System.out.println("Printing the Unsorted HashMap");
        for(Entry<String, Integer> e : unsortedMap.entrySet()) {
            System.out.println(e.getKey() + "-->" + e.getValue());
        }

        Stream<Entry<String, Integer>> sortedStream = unsortedMap.entrySet()
                                        .stream()
                                        .sorted(Map.Entry.<String, Integer>comparingByValue());

        System.out.println("\nPrinting the Sorted Key-Value Pairs");
        sortedStream.forEach(System.out :: println);
    }
}

The code above is sorting the HashMap by values using Java Streams and Lambda expressions.

Use the following command to compile and run the code:

javac HashMapSortDemo.java && java HashMapSortDemo

Using Google's Guava Library

Google's Guava library provides us an ImmutableSortedMap class. We can use the copyOf() method of this class to sort a HashMap. Follow the code below:

import java.util.HashMap;
import java.util.Map.Entry;
import com.google.common.collect.ImmutableSortedMap;

public class HashMapSortDemo {
    public static void main(String args[]) {
        HashMap<String, Integer> unsortedMap = new HashMap<>();
        unsortedMap.put("one", 1);
        unsortedMap.put("two", 2);
        unsortedMap.put("three", 3);
        unsortedMap.put("four", 4);
        unsortedMap.put("five", 5);

        System.out.println("Printing the Unsorted HashMap");
        for (Entry<String, Integer> e : unsortedMap.entrySet()) {
            System.out.println(e.getKey() + "-->" + e.getValue());
        }

        ImmutableSortedMap<String, Integer> sortedMap = ImmutableSortedMap.copyOf(unsortedMap);

        System.out.println("\nPrinting the Sorted ImmutableSortedMap");
        System.out.println(sortedMap);
    }
}

The code above is sorting the HashMap using Google's Guava library.

Use the following command to compile and run the code:

javac -cp ".:guava-30.1.1-jre.jar" HashMapSortDemo.java && java -cp ".:guava-30.1.1-jre.jar" HashMapSortDemo

Cleaning up

Finally, delete the HashMapSortDemo.java file using the following command:

rm HashMapSortDemo.java

Summary

In this lab, we have seen how to sort a HashMap by keys or values. We used different methods like Collections.sort(), TreeMap, TreeSet, Java Streams and Lambda expressions, and Google's Guava library for sorting the HashMap. We also learned about their use cases and how we can write an efficient code to sort the HashMap in Java.

Other Java Tutorials you may like