Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

sort
java
hashmap

How to sort a Java HashMap by value

Educative Answers Team

A HashMap can be sorted by its keys or its values. However, a problem that HashMap has is that its iteration order, when considering a sorted data structure, is not preserved. This makes it difficult to display sorted data.

One solution to this problem is to use the LinkedHashMap class in Java; this class maintains the iteration order. In fact, any other class will work as well, provided that it keeps the iteration order the same.

Since a LinkedHashMap keeps key-value pairs in the insertion order, the following will be our procedure to get a sorted LinkedHashMap:

svg viewer

Sorting a HashMap by value

  1. Extract the HashMap’s entries (using HashMap.entrySet()) and input them into an ArrayList (has elements of type Map.Entry<String, Integer>) with a simple for-each loop:
for(Map.Entry<String, Integer> e: hashMap.entrySet()) {
			arr.add(e);
}
  1. Sort this ArrayList using Collections.sort(). As the elements of this ArrayList are of type Map.Entry<String, Integer>, we need to write our own Comparator code to sort the elements:
Comparator<Map.Entry<String, Integer>> myComparator =
new Comparator<Map.Entry<String, Integer>>() {
            
            @Override
            public int compare(
                  Map.Entry<String, Integer> e1,
                  Map.Entry<String, Integer> e2) {

                Integer int1 = e1.getValue();
                Integer int2 = e2.getValue();
                return int1.compareTo(int2);
            }
};

// Sorting the list w.r.t values of entries using myComparator
Collections.sort(list, myComparator);
  1. Add all the elements (or entries) of the sorted ArrayList to a LinkedHashMap:
for(Map.Entry<String, Integer> e: list) {
			linkedMap.put(e.getKey(), e.getValue());
}
  1. Finally, we can print our LinkedHashMap; the data will be sorted:
for(Map.Entry<String, Integer> e: linkedMap) {
			System.out.println(e.getValue());
}

Example code

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class HashMapSorting {
  HashMap<String, Integer> map;
  LinkedHashMap<String, Integer> linkedMap;
  ArrayList<Map.Entry<String, Integer>> arr;

	public void sort() {				
    for(Map.Entry<String, Integer> e: map.entrySet()) {
			arr.add(e);
		}

		Comparator<Map.Entry<String, Integer>> valueComparator = new Comparator<Map.Entry<String, Integer>>() {
            
            @Override
            public int compare(Map.Entry<String, Integer> e1, Map.Entry<String, Integer> e2) {
                Integer v1 = e1.getValue();
                Integer v2 = e2.getValue();
                return v1.compareTo(v2);
            }
    };

		Collections.sort(arr, valueComparator);

		for(Map.Entry<String, Integer> e: arr) {
			linkedMap.put(e.getKey(), e.getValue());
			System.out.println(e.getValue());
		}
	}

  HashMapSorting(){
    map = new HashMap<>();

    map.put("a", 10);
		map.put("b", 30);
		map.put("c", 20);
		map.put("d", 5);
		map.put("e", 40);

    linkedMap = new LinkedHashMap<>();
    arr = new ArrayList<>();
  }

  public static void main(String[] args) {
		HashMapSorting m = new HashMapSorting();
		m.sort();
	}
}

RELATED TAGS

sort
java
hashmap
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring