Java – How to sort LinkedHashMap by its Keys ?

In this article, we will discuss how to convert ordered LinkedHashMap into Sorted TreeMap by its Keys

With the introduction of Java 8 APIs, sorting LinkedHashMap become easy and more elegant, read below articles

1. Sorting LinkedHashMap in ascending order of Keys :

  • LinkedHashMap maintains insertion-order of keys
  • For Ascending order sorting, pass LinkedHashMap entries as constructor-argument to TreeMap class’ inter-conversion constructor
  • In below illustration, we will sort/convert LinkedHashMap into natural-ordering of keys
  • Syntax :-
// convert to TreeMap
Map<String, String> ts = new TreeMap<String, String>(linkMap);

SortingLinkedHashMapInAscOrder.java

package in.bench.resources.collection;

import java.util.LinkedHashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class SortingLinkedHashMapInAscOrder {

	public static void main(String[] args) {

		// 1. create LinkedHashMap object of type <String, String>
		LinkedHashMap<String, String> linkMap =
				new LinkedHashMap<String, String>();


		// 1.1 adding key-value pairs to LinkedHashMap object
		linkMap.put("Microsoft", "Bill Gates");
		linkMap.put("Apple Inc", "Steve Jobs");
		linkMap.put("Google", "Sundar Pichai");
		linkMap.put("LinkedIn", "Reid Hoffman");
		linkMap.put("Facebook", "Mark Zuckerberg");


		// 1.2 Insertion-Order iterating
		System.out.println("Before Sorting : Insertion-Order \n");


		// 1.3 getting keySet() into Set
		Set<String> set = linkMap.keySet();


		// 1.4 get Iterator from key set
		Iterator<String> itr = set.iterator();


		// 1.5 iterating in Insertion-order
		while(itr.hasNext()) {
			String key = itr.next();
			System.out.println("Key : "  + key
					+ "\t\t" + "Value : "  + linkMap.get(key));
		}


		// 2. After Sorting : Ascending order
		System.out.println("\n\n\nAfter Sorting : Ascending-Order\n");


		// 2.1 convert to TreeMap
		Map<String, String> ts = new TreeMap<String, String>(linkMap);


		// 2.2 iterate - ascending order of keys
		for(String strKey : ts.keySet()){
			System.out.println("Key : "  + strKey
					+ "\t\t" + "Value : "  + linkMap.get(strKey));
		}
	}
}

Output:

Before Sorting : Insertion-Order 

Key : Microsoft		Value : Bill Gates
Key : Apple Inc		Value : Steve Jobs
Key : Google		Value : Sundar Pichai
Key : LinkedIn		Value : Reid Hoffman
Key : Facebook		Value : Mark Zuckerberg



After Sorting : Ascending-Order

Key : Apple Inc		Value : Steve Jobs
Key : Facebook		Value : Mark Zuckerberg
Key : Google		Value : Sundar Pichai
Key : LinkedIn		Value : Reid Hoffman
Key : Microsoft		Value : Bill Gates

2. Sorting LinkedHashMap in descending order of keys :

  • LinkedHashMap maintains insertion-order of keys
  • Descending order :- Implement Comparator interface while creating new TreeMap by providing reverse sorting logic
  • Finally put all entries of LinkedHashMap into TreeMap class using putAll() method
  • In below illustration, we will sort/convert LinkedHashMap into reverse-ordering of keys
  • Syntax :-
// convert to TreeMap
// descending or reverse-order sorting logic
Map<String, String> tMap = new TreeMap<String, String>(
				new Comparator<String>() {

					@Override
					public int compare(String str1, String str2) {
						return str2.compareTo(str1);
					}
				});

		// put all key-value into TreeMap
		tMap.putAll(linkMap);

SortingLinkedHashMapInDesOrder.java

package in.bench.resources.collection;

import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class SortingLinkedHashMapInDesOrder {

	public static void main(String[] args) {

		// 1. create LinkedHashMap object of type <String, String>
		LinkedHashMap<String, String> linkMap =
				new LinkedHashMap<String, String>(); 


		// 1.1 adding key-value pairs to LinkedHashMap object
		linkMap.put("Microsoft", "Bill Gates");
		linkMap.put("Apple Inc", "Steve Jobs");
		linkMap.put("Google", "Sundar Pichai");
		linkMap.put("LinkedIn", "Reid Hoffman");
		linkMap.put("Facebook", "Mark Zuckerberg");


		// 1.2 Insertion-Order iterating
		System.out.println("Before Sorting : Insertion-Order \n");


		// 1.3 getting keySet() into Set
		Set<String> set = linkMap.keySet();


		// 1.4 get Iterator from key set
		Iterator<String> itr = set.iterator();


		// 1.5 iterating in insertion-order
		while(itr.hasNext()) {
			String key = itr.next();
			System.out.println("Key : "  + key
					+ "\t\t" + "Value : "  + linkMap.get(key));
		}


		// 2. After Sorting : Descending order
		System.out.println("\n\n\nAfter Sorting : Descending-Order\n");


		// 2.1 descending or reverse-order sorting logic
		Map<String, String> tMap = new TreeMap<String, String>(
				new Comparator<String>() {

					@Override
					public int compare(String str1, String str2) {
						return str2.compareTo(str1);
					}
				});


		// 2.2 put all key-value into TreeMap
		tMap.putAll(linkMap);


		// 2.3 iterate - descending order of keys
		for(String strKey : tMap.keySet()){
			System.out.println("Key : "  + strKey
					+ "\t\t" + "Value : "  + linkMap.get(strKey));
		}
	}
}

Output:

Before Sorting : Insertion-Order 

Key : Microsoft		Value : Bill Gates
Key : Apple Inc		Value : Steve Jobs
Key : Google		Value : Sundar Pichai
Key : LinkedIn		Value : Reid Hoffman
Key : Facebook		Value : Mark Zuckerberg



After Sorting : Descending-Order

Key : Microsoft		Value : Bill Gates
Key : LinkedIn		Value : Reid Hoffman
Key : Google		Value : Sundar Pichai
Key : Facebook		Value : Mark Zuckerberg
Key : Apple Inc		Value : Steve Jobs

Important points to remember about Map :

  • HashMap stores entries (Key-Value pairs) in random-order of Keys
  • LinkedHashMap stores entries (Key-Value pairs) as per insertion-order of Keys
  • TreeMap stores entries (Key-Value pairs) in sorted-order of Keys

References:

Happy Coding !!
Happy Learning !!

Java - How to sort LinkedHashMap by its Values ?
How to sort LinkedHashSet contents in Java ?