Thursday, August 5, 2021

How to sort an HashMap based on value

 
 

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class SortHashMapByValue {

	public static void main(String[] args) {

		HashMap<String,Integer> unsortMap = new HashMap<String, Integer>();
		unsortMap.put("Ram", 10);
		unsortMap.put("Syam", 50);
		unsortMap.put("Radhe", 5);
		unsortMap.put("Krishna", 80);
		unsortMap.put("Suneel", 20);
		
		System.out.println("Before sorting:");
		printMap(unsortMap);
        
		System.out.println("\n");
		System.out.println("Sorting sorting:");
		HashMap<String,Integer> sortedMap = (sortHashMap(unsortMap));
		printMap(sortedMap);
		
	}

	private static HashMap<String, Integer> sortHashMap(HashMap<String, Integer> unsortMap) {
		List<Entry<String, Integer>> list = new LinkedList<Map.Entry<String,Integer>>(unsortMap.entrySet());
		Collections.sort(list, new Comparator<Map.Entry<String,Integer>>() {

			@Override
			public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
				
				return o1.getValue().compareTo(o2.getValue());
			}
		});
		
		LinkedHashMap<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
		for (Entry<String, Integer> entry : list) {
			sortedMap.put(entry.getKey(), entry.getValue());
		}
		return sortedMap;
	}

	private static void printMap(HashMap<String, Integer> unsortMap) {
		
		for(Entry<String, Integer> entry : unsortMap.entrySet()) {
			
			System.out.println("The Key is :- "+entry.getKey()+" The Value is:- "+entry.getValue());
		}
	}

}

Output:-

Before sorting: The Key is :- Radhe The Value is:- 5 The Key is :- Krishna The Value is:- 80 The Key is :- Syam The Value is:- 50 The Key is :- Suneel The Value is:- 20 The Key is :- Ram The Value is:- 10 Sorting sorting: The Key is :- Radhe The Value is:- 5 The Key is :- Ram The Value is:- 10 The Key is :- Suneel The Value is:- 20 The Key is :- Syam The Value is:- 50 The Key is :- Krishna The Value is:- 80

No comments:

Post a Comment

How to sort an HashMap based on value

import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedHashMap; import java....