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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/FileandIOManagementGroup(["`File and I/O Management`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/generics("`Generics`") java/FileandIOManagementGroup -.-> java/stream("`Stream`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/arraylist("`ArrayList`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/hashmap("`HashMap`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("`Wrapper Classes`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/sorting("`Sorting`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/for_loop("`For Loop`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/DataStructuresGroup -.-> java/collections_methods("`Collections Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117985{{"`Sorting a HashMap`"}} java/generics -.-> lab-117985{{"`Sorting a HashMap`"}} java/stream -.-> lab-117985{{"`Sorting a HashMap`"}} java/arraylist -.-> lab-117985{{"`Sorting a HashMap`"}} java/classes_objects -.-> lab-117985{{"`Sorting a HashMap`"}} java/class_methods -.-> lab-117985{{"`Sorting a HashMap`"}} java/hashmap -.-> lab-117985{{"`Sorting a HashMap`"}} java/modifiers -.-> lab-117985{{"`Sorting a HashMap`"}} java/oop -.-> lab-117985{{"`Sorting a HashMap`"}} java/packages_api -.-> lab-117985{{"`Sorting a HashMap`"}} java/wrapper_classes -.-> lab-117985{{"`Sorting a HashMap`"}} java/identifier -.-> lab-117985{{"`Sorting a HashMap`"}} java/sorting -.-> lab-117985{{"`Sorting a HashMap`"}} java/data_types -.-> lab-117985{{"`Sorting a HashMap`"}} java/for_loop -.-> lab-117985{{"`Sorting a HashMap`"}} java/operators -.-> lab-117985{{"`Sorting a HashMap`"}} java/output -.-> lab-117985{{"`Sorting a HashMap`"}} java/strings -.-> lab-117985{{"`Sorting a HashMap`"}} java/collections_methods -.-> lab-117985{{"`Sorting a HashMap`"}} java/system_methods -.-> lab-117985{{"`Sorting a HashMap`"}} end

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