Skip to content

Sort a HashMap in Java 8 by Key or Value

HashMap in Java does not maintain insertion order either by key or by order. Also it does not maintain any other order while adding entries to it.

Using Java 8 you can sort a HashMap with the following steps.

  • Get all entries by calling entrySet() method of Map.
  • Create a custom Comparator to sort entries based upon values/keys.
  • Convert entry set to list. Sort entry list by using Collections.sort() method by passing your value/key comparator.
  • Create a LinkedHashMap by adding entries in sorted order.
package com.poopcode.examples;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import java.util.stream.Stream;


/**
 * @author PoopCode
 *
 */
public class HashMapSortExample {

	private static Random random = new Random();

	public static void main(String[] argv) {

		Map<String, Integer> map = new HashMap<>();
		
		ArrayList<String> letters = new ArrayList<>();
		letters.add("A");
		letters.add("B");
		letters.add("C");
		letters.add("D");

		for (int i = 1; i <= 10; ++i) {
			map.put(String.valueOf(random.nextInt(10))+ letters.get(random.nextInt(letters.size())), random.nextInt(50));
		}

		System.out.println("==========================ORIGINAL MAP==============================");
		System.out.println(map);

		System.out.println("==========================MAP AFTER SORTING BY KEY==============================");
		sortHashMapByKey(map).forEach((k, v) -> {
			System.out.println("Key: " + k + "\t\t Value: " + v);
		});

		System.out.println("==========================MAP AFTER SORTING BY VALUE==============================");
		sortHashMapByValue(map).forEach((k, v) -> {
			System.out.println("Key: " + k + "\t\t Value: " + v);
		});

	}

	// SORTING HASHMAP BY KEY
	public static <K extends Comparable<? super K>, V> Map<K, V> sortHashMapByKey(Map<K, V> map) {

		Map<K, V> sortedMap = new LinkedHashMap<>();
		Stream<Map.Entry<K, V>> stream = map.entrySet().stream();

		// comparingByKey() returns a comparator that compares Map.Entry in natural
		// order of key.
		stream.sorted(Map.Entry.comparingByKey()).forEachOrdered(c -> sortedMap.put(c.getKey(), c.getValue()));
		return sortedMap;
	}

	// SORTING HASHMAP BY VALUE
	public static <K, V extends Comparable<? super V>> Map<K, V> sortHashMapByValue(Map<K, V> map) {

		Map<K, V> sortedMap = new LinkedHashMap<>();
		Stream<Map.Entry<K, V>> stream = map.entrySet().stream();

		// comparingByKey() returns a comparator that compares Map.Entry in natural
		// order of key.
		stream.sorted(Map.Entry.comparingByValue()).forEachOrdered(c -> sortedMap.put(c.getKey(), c.getValue()));
		return sortedMap;
	}

}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.