How to Sort a HashMap by Value in Java?

To Sort a HashMap by Value in Java, we are perform following step :-

  • HashMap store items in “key, value” pairs. To get a value from the HashMap, we use the key corresponding to that entry.
  • First we create the hashmap object and store the key, value data.
  • From h.entrySet() method take only unique hashmap key data.
  • Now pass this Set() data to arraylist class.
  • Now use the Collections.sort() method to sort the data.
  • From Comparator interface, we call the compare() method for customized sorting.
  • This method compare from the first value to second value.

               Syntax :- (m1.getValue()).compareTo(m2.getValue()

  • After sorting this list,pass to for loop to fetch the data from map.getKey() and map.getValue().
				
					import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class OrderByValue {
	public static void main(String[] args) {
		HashMap<String, Integer> h = new HashMap<String, Integer>();
		h.put("java", 35);
		h.put("spring", 3);
		h.put("jsp", 24);
		h.put("core", 2);
		h.put("servlet", 89);
		Set<Entry<String, Integer>> st = h.entrySet();
		List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(st);

		Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
			public int compare(Map.Entry<String, Integer> m1, Map.Entry<String, Integer> m2) {
				return (m1.getValue()).compareTo(m2.getValue());
			}
		});
		System.out.println("sort by value :- ");
		for (Map.Entry<String, Integer> map : list) {
			System.out.println("key :- "+map.getKey() + " ,value :- " + map.getValue());
		}
	}
}
				
			

Output :-
sort by value :-
key :- core ,value :- 2
key :- spring ,value :- 3
key :- jsp ,value :- 24
key :- java ,value :- 35
key :- servlet ,value :- 89