Overview

Hashmap is a hashing data structure that uses hashing technique to store key-value pairs, such that keys of no 2 pairs are equal. In this article, we shall look at different techniques of how to sort the entries of a hashmap in Java.

Scope

This article shall cover:

  • Sorting Java hashmap using a TreeMap.
  • Sorting Java hashmap using an ArrayList.
  • Sorting Java hashmap using Java 8 lambda.
  • Sorting Java hashmap using Java stream.

This article shall not deal with:

  • Hashmap data structure internals.
  • Any other unrelated Java concepts.

Using TreeMap

TreeMap in Java is a container based on Red-black tees that stores items in it in a sorted fashion. In the code block ahead, as we add the key-value pairs from HashMap to a TreeMap, the TreeMap naturally inserts the pairs in itself in sorted order by keys.

import java.util.*;
class Main{
static Map<String, Integer> map = new HashMap<>();
public static void sortbykey(){
TreeMap<String, Integer> sorted = new TreeMap<>();
sorted.putAll(map);
for (Map.Entry<String, Integer> entry : sorted.entrySet()){
System.out.println("k : " + entry.getKey() + " | v : " + entry.getValue());
}
}
public static void main(String args[]){
map.put("alpha", 0);
map.put("theta", 2);
map.put("gamma", 3);
map.put("omega", 1);
sortbykey();
}
}

Output

k : alpha | v : 0
k : gamma | v : 3
k : omega | v : 1
k : theta | v : 2

Alternative

We can also construct the TreeMap and pass the HashMap object as an argument to the constructor. This way we need not explicitly call “puAll()”.

import java.util.*;

class Main{
static Map<String, Integer> map = new HashMap<>();
public static void sortbykey(){
    TreeMap<String, Integer> sorted = new TreeMap<>(map);
for (Map.Entry<String, Integer> entry : sorted.entrySet()){
System.out.println("k : " + entry.getKey() + " | v : " + entry.getValue());
}
}
public static void main(String args[]){
map.put("alpha", 0);
map.put("theta", 2);
map.put("gamma", 3);
map.put("omega", 1);
sortbykey();
}
}

Output

k : alpha | v : 0
k : gamma | v : 3
k : omega | v : 1
k : theta | v : 2

Using ArrayList

In this method, we first store all the entries of the hashmap in an ArrayList container and then sort the ArrayList object.

import java.util.*;
class Main{
static Map<String, Integer> map = new HashMap<>();
public static void sortbykey(){
    ArrayList<String> sortedKeys = new ArrayList<String>(map.keySet());
        Collections.sort(sortedKeys);
        for(String x : sortedKeys){
            System.out.println("k : " + x + " | v : " + map.get(x));
        }
}
public static void main(String args[]){
map.put("alpha", 0);
map.put("theta", 2);
map.put("gamma", 3);
map.put("omega", 1);
sortbykey();
}
}

Output

k : alpha | v : 0
k : gamma | v : 3
k : omega | v : 1
k : theta | v : 2

Using Java 8 lambda expressions

In this method the way we sort changes as it will now be using a lambda expression.

import java.util.*;
class Main{
static Map<String, Integer> map = new HashMap<>();
public static Map<String, Integer>
sortByKey(Map<String, Integer> hm){
List<Map.Entry<String, Integer> > list = new LinkedList<Map.Entry<String, Integer>>(hm.entrySet());
Collections.sort(list, (i1, i2) -> i1.getKey().compareTo(i2.getKey()));
HashMap<String, Integer> ret = new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> entry : list) {
ret.put(entry.getKey(), entry.getValue());
}
return ret;
}
public static void main(String args[]){
map.put("alpha", 0);
map.put("theta", 1);
map.put("gamma", 2);
map.put("omega", 3);
Map<String, Integer> hm1 = sortByKey(map);
for (Map.Entry<String, Integer> en : hm1.entrySet()) {
System.out.println("k : " + en.getKey() + " | v : " + en.getValue());
}
}
}

Output

k : alpha | v : 0
k : gamma | v : 2
k : omega | v : 3
k : theta | v : 1

Using Java 8 stream

In this method, we call “stream()” which returns a stream of entrySet followed. This is followed by the usage of lambda expression inside the “sorted()” function to sort the stream. Finally, we use the “toMap()” function to convert it into a map. We’ll have to use the LinkedHashMap::new method reference in the toMap call for retaining the map’s sorted order.

import static java.util.stream.Collectors.*;
import java.lang.*;
import java.util.*;
import java.util.stream.*;
import java.util.stream.Collectors;
public class Main {
static Map<String, Integer> map = new HashMap<>();
public static void sortbykey(){
HashMap<String, Integer> tmp = map.entrySet().stream().sorted((a, b) -> a.getKey().compareTo(b.getKey())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (x, y) -> x, LinkedHashMap::new));
for (Map.Entry<String, Integer> entry : tmp.entrySet()) {
System.out.println("k : " + entry.getKey() + " | v : " + entry.getValue());
}
}
public static void main(String args[]){
    map.put("alpha", 0);
map.put("theta", 1);
map.put("gamma", 2);
map.put("omega", 3);
sortbykey();
}
}

Output

k : alpha | v : 0
k : gamma | v : 2
k : omega | v : 3
k : theta | v : 1