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
 
Thursday, August 5, 2021
How to sort an HashMap based on value
Subscribe to:
Post Comments (Atom)
How to find middle node of LinkedList without using extra memory in java
To find the middle node of a LinkedList without using extra memory in Java, you can use the "tortoise and hare" algorithm. This al...
- 
public class ReverseArrayWithoutExtraMemory { public static void main(String[] args) { int arr[] = {1,2,3,4,5,6}; int swapArray[] =...
- 
public class SumPair { public static void main(String[] args) { int arr[] = {5,7,8,3,1,4,6,9,2}; int n = 12; findPair(arr,n); ...
- 
1) List Interface Implementation public interface List<T extends Comparable<T>> { public Node<T> getMi...
 
 
No comments:
Post a Comment