Java – How to sort LinkedHashMap by its Values ?

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

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

1. Sorting LinkedHashMap in ascending order of values :

1.1 Ascending-order sorting steps :-

  1. get entrySet() from Map
  2. create/convert entry set into List of entries
  3. sort converted List using Collections class’ sort(); method by implementing Comparator for natural-ordering by its Values
  4. clear original LinkedHashMap using clear(); method
  5. Iterate List and add entries to original LinkedHashMap, after clearing
  6. finally print Map.Entry in console

1.2 Ascending-order Sorting of LinkedHashMap by its values :

  • LinkedHashMap maintains insertion-order of keys
  • In below illustration, we will sort/convert LinkedHashMap into natural-ordering of values i.e.; ascending-order of values

SortingLinkedHashMapInAscOrderByValues.java

package in.bench.resources.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class SortingLinkedHashMapInAscOrderByValues {

	public static void main(String[] args) {

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


		// adding key-value pairs to LinkedHashMap object
		linkMap.put("Google", "Sundar Pichai");
		linkMap.put("Facebook", "Mark Zuckerberg");
		linkMap.put("LinkedIn", "Reid Hoffman");
		linkMap.put("Apple Inc", "Tim Cook");
		linkMap.put("Microsoft", "Bill Gates");
		linkMap.put("Amazon", "Jeff Bezos");
		linkMap.put("Oracle", "Larry Ellison");


		System.out.println("Before Sorting by Values -"
				+ " as per insertion-order : \n");

		// iterate original LinkedHashMap
		for(Map.Entry<String, String> lhmap :
			linkMap.entrySet()){
			System.out.println("Key : "  + lhmap.getKey()
			+ "\t\t" + "Value : "  + lhmap.getValue());
		}


		// 1. get entrySet from LinkedHashMap object
		Set<Map.Entry<String, String>> companyFounderSet =
				linkMap.entrySet();


		// 2. convert LinkedHashMap to List of Map.Entry
		List<Map.Entry<String, String>> companyFounderListEntry =
				new ArrayList<Map.Entry<String, String>>(
						companyFounderSet);


		// 3. sort list of entries using Collections class'
		// utility method sort(ls, cmptr)
		Collections.sort(companyFounderListEntry,
				new Comparator<Map.Entry<String, String>>() {

			@Override
			public int compare(Entry<String, String> es1,
					Entry<String, String> es2) {
				return es1.getValue().compareTo(es2.getValue());
			}
		});


		// 4. clear original LinkedHashMap
		linkMap.clear();


		// 5. iterating list and storing in LinkedHahsMap
		for(Map.Entry<String, String> map : companyFounderListEntry){
			linkMap.put(map.getKey(), map.getValue());
		}


		System.out.println("\n\nSorted LinkedHashMap by its Values"
				+ " in ascending-order\n");


		// 6. iterate LinkedHashMap to retrieved stored values
		for(Map.Entry<String, String> lhmap :
			linkMap.entrySet()){
			System.out.println("Key : "  + lhmap.getKey()
			+ "\t\t" + "Value : "  + lhmap.getValue());
		}
	}
}

Output:

Before Sorting by Values - as per insertion-order : 

Key : Google		Value : Sundar Pichai
Key : Facebook		Value : Mark Zuckerberg
Key : LinkedIn		Value : Reid Hoffman
Key : Apple Inc		Value : Tim Cook
Key : Microsoft		Value : Bill Gates
Key : Amazon		Value : Jeff Bezos
Key : Oracle		Value : Larry Ellison


Sorted LinkedHashMap by its Values in ascending-order

Key : Microsoft		Value : Bill Gates
Key : Amazon		Value : Jeff Bezos
Key : Oracle		Value : Larry Ellison
Key : Facebook		Value : Mark Zuckerberg
Key : LinkedIn		Value : Reid Hoffman
Key : Google		Value : Sundar Pichai
Key : Apple Inc		Value : Tim Cook

2. Sorting LinkedHashMap in descending order of Values :

1.1 Descending-order sorting steps :-

  1. get entrySet() from Map
  2. create/convert entry set into List of entries
  3. sort converted List using Collections class’ sort(); method by implementing Comparator for reverse sorting logic by its Values
  4. clear original LinkedHashMap using clear(); method
  5. Iterate List and add entries to original LinkedHashMap, after clearing
  6. finally print Map.Entry in console

1.2 Descending-order Sorting of LinkedHashMap by its values :

  • LinkedHashMap maintains insertion-order of keys
  • In below illustration, we will sort/convert LinkedHashMap into reverse-ordering of Values i.e.; descending-order of values

SortingLinkedHashMapInDesOrderByValues.java

package in.bench.resources.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

public class SortingLinkedHashMapInDesOrderByValues {

	public static void main(String[] args) {

		// creating LinkedHashMap object of type <String, String>
		Map<String, String> linkMap =
				new LinkedHashMap<String, String>();


		// adding key-value pairs to LinkedHashMap object
		linkMap.put("Google", "Sundar Pichai");
		linkMap.put("Facebook", "Mark Zuckerberg");
		linkMap.put("LinkedIn", "Reid Hoffman");
		linkMap.put("Apple Inc", "Tim Cook");
		linkMap.put("Microsoft", "Bill Gates");
		linkMap.put("Amazon", "Jeff Bezos");
		linkMap.put("Oracle", "Larry Ellison");


		System.out.println("Before Sorting by Values -"
				+ " as per insertion-order : \n");


		// iterate original LinkedHashMap
		for(Map.Entry<String, String> lhmap :
			linkMap.entrySet()){
			System.out.println("Key : "  + lhmap.getKey()
			+ "\t\t" + "Value : "  + lhmap.getValue());
		}


		// 1. get entrySet from LinkedHashMap object
		Set<Map.Entry<String, String>> companyFounderSet =
				linkMap.entrySet();


		// 2. convert LinkedHashMap to List of Map.Entry
		List<Map.Entry<String, String>> companyFounderListEntry =
				new ArrayList<Map.Entry<String, String>>(
						companyFounderSet);


		// 3. sort list of entries using Collections class'
		// utility method sort(ls, cmptr)
		Collections.sort(companyFounderListEntry,
				new Comparator<Map.Entry<String, String>>() {

			@Override
			public int compare(Entry<String, String> es1,
					Entry<String, String> es2) {
				return es2.getValue().compareTo(es1.getValue());
			}
		});


		// 4. clear original LinkedHashMap
		linkMap.clear();


		// 5. iterating list and storing in LinkedHahsMap
		for(Map.Entry<String, String> map : companyFounderListEntry){
			linkMap.put(map.getKey(), map.getValue());
		}


		System.out.println("\n\nSorted LinkedHashMap by its Values"
				+ " in descending-order\n");


		// 6. iterate LinkedHashMap to retrieved stored values
		for(Map.Entry<String, String> lhmap :
			linkMap.entrySet()){
			System.out.println("Key : "  + lhmap.getKey()
			+ "\t\t" + "Value : "  + lhmap.getValue());
		}
	}
}

Output:

Before Sorting by Values - as per insertion-order : 

Key : Google		Value : Sundar Pichai
Key : Facebook		Value : Mark Zuckerberg
Key : LinkedIn		Value : Reid Hoffman
Key : Apple Inc		Value : Tim Cook
Key : Microsoft		Value : Bill Gates
Key : Amazon		Value : Jeff Bezos
Key : Oracle		Value : Larry Ellison


Sorted LinkedHashMap by its Values in descending-order

Key : Apple Inc		Value : Tim Cook
Key : Google		Value : Sundar Pichai
Key : LinkedIn		Value : Reid Hoffman
Key : Facebook		Value : Mark Zuckerberg
Key : Oracle		Value : Larry Ellison
Key : Amazon		Value : Jeff Bezos
Key : Microsoft		Value : Bill Gates

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 !!

Conversion of ArrayList to Arrays in Java - 2 ways
Java - How to sort LinkedHashMap by its Keys ?