HomeLanguagesJavaSort LinkedHashMap by Keys in Java

Sort LinkedHashMap by Keys in Java

LinkedHashMap maintains insertion order. Convert LinkedHashMap into TreeMap and after that print keys of TreeMap which are sorted in nature.  

Example:

Input: linkedHashMap = {{5,4}, {3,44}, {4,15}, {1,20}, {2,11}}
Output:
key -> 1 : value -> 20
key -> 2 : value -> 11
key -> 3 : value -> 44
key -> 4 : value -> 15 
key -> 5: value -> 4

Approach:

  1. Take LinkedHashMap as an input.
  2. Create new TreeMap.
  3. Pass LinkedHashMap object into the constructor of TreeMap.
  4. Print Keys of TreeMap object.

Below is the implementation of the above approach:

Java




// Sort LinkedHashMap by keys in Java
import java.util.*;
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        LinkedHashMap<Integer, Integer> lMap
            = new LinkedHashMap<>();
  
        // adding key-value pairs to LinkedHashMap object
        lMap.put(5, 4);
        lMap.put(3, 44);
        lMap.put(4, 15);
        lMap.put(1, 20);
        lMap.put(2, 11);
        System.out.println("After Sorting :\n");
  
        // convert to TreeMap
        Map<Integer, Integer> map = new TreeMap<>(lMap);
  
        // iterate acc to ascending order of keys
        for (Integer sKey : map.keySet()) {
            System.out.println("Key -> " + sKey
                               + ":  Value -> "
                               + lMap.get(sKey));
        }
    }
}


Output

After Sorting :

Key -> 1:  Value -> 20
Key -> 2:  Value -> 11
Key -> 3:  Value -> 44
Key -> 4:  Value -> 15
Key -> 5:  Value -> 4
RELATED ARTICLES

2 COMMENTS

Most Popular

Dominic
32548 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6923 POSTS0 COMMENTS
Nicole Veronica
12039 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12150 POSTS0 COMMENTS
Shaida Kate Naidoo
7060 POSTS0 COMMENTS
Ted Musemwa
7302 POSTS0 COMMENTS
Thapelo Manthata
7018 POSTS0 COMMENTS
Umr Jansen
7006 POSTS0 COMMENTS