Reputation: 308
Continuation from my previous question posted Sorting a map in java
I am trying out a solution to sort a tree map based on its values
Let me declare the Map
Map<String, List<Bean>> sortedBeanMap =new TreeMap<String,List<Bean>>();
i have created a separate comparator method to compare the values .
public class MapSort {
public static Map sortByValue(Map unsortedMap){
Map sortedMap = new TreeMap(new ValueComparator(unsortedMap));
sortedMap.putAll(unsortedMap);
return sortedMap;
}
public static Map sortByKey(Map unsortedMap){
Map sortedMap = new TreeMap();
sortedMap.putAll(unsortedMap);
return sortedMap;
}
}
ValueComparator class
public class ValueComparator implements Comparator {
Map map;
public ValueComparator(Map map){
this.map = map;
}
public int compare(Object keyA, Object keyB){
Comparable valueA = (Comparable) map.get(keyA);
Comparable valueB = (Comparable) map.get(keyB);
System.out.println(valueA +" - "+valueB);
return valueA.compareTo(valueB);
}
}
I knew the values should be of type string for the comparable to Work.But in my case , it will be a bean list.So how to get the comparator to work for my case ?
i am stuck in this for a while ..Any suggestions and ideas would be great .
Thanks guys in advance...
Upvotes: 0
Views: 518
Reputation: 4843
Since this is homework full code won't be supplied.
You are on the right track. Do create a class for your objects and implement the required methods for Comparable. You can decide what the "order" should be for two of your objects that have a list of beans: should on be smaller than another because the number of list elements are less; because the individual list elements have names that are "smaller"; or another well-defined ordering?
Upvotes: 1