0 votes
13.5k views
in Java by
How to sort map based on values in java ?

1 Answer

0 votes
by
To sort map on the basis of map values.
See the following steps and code for sorting map based on map values:
 
Step 1: Create a Map (Map<String, Integer> userRatingMap = new HashMap<String, Integer>()).
Step 2: Add values in map.
Step 3: Create a Comparator class (CompareMapByValue.java) to comapare the map values.
Step 4: Create a TreeMap and put our created Comparator class (CompareMapByValue.java) refrance.
Step 5: Put all Map values into TreeMap.
Step 6: See the following code for better understanding.
 
SortMapByValue.java (Main class):
package test.com.alg;
 
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
 
public class SortMapByValue {
public static void main(String[] args) {
Map<String, Integer> userRatingMap = new HashMap<String, Integer>();
userRatingMap.put("Karan", 3);
userRatingMap.put("Pawan", 5);
userRatingMap.put("Suman", 1);
userRatingMap.put("Rinku", 4);
userRatingMap.put("Jiya", 2);
 
System.out.println(userRatingMap);
 
CompareMapByValue Compare = new CompareMapByValue(userRatingMap);
TreeMap<String, Integer> treemap = new TreeMap<String, Integer>(Compare);
treemap.putAll(userRatingMap);
 
System.out.println(treemap);
}
}
 
CompareMapByValue.java (Comparator Class):
package test.com.alg;
 
import java.util.Comparator;
import java.util.Map;
 
public class CompareMapByValue implements Comparator<String>{
 
Map<String, Integer> map;
public CompareMapByValue(Map<String, Integer> map) {
this.map = map;
}
 
public int compare(String o1, String o2) {
return map.get(o1).compareTo(map.get(o2));
}
}
 
Output:
{Rinku=4, Jiya=2, Suman=1, Karan=3, Pawan=5}
{Suman=1, Jiya=2, Karan=3, Rinku=4, Pawan=5}
 

Share:- Whatsapp Facebook Facebook


Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

...