But Im not very clear on how to pass back the value into tree map after sorting using comparator?
That's not the idea.
Create a TreeMap and pass your own custom Comparator to it (to the constructor of TreeMap). The Comparator is a class that implements interface Comparator and it decides the order of elements in the map.
After creating the TreeMap, add the elemens to the map in any order you like. The TreeMap automatically sorts them while you add them.
Hi,
Thanks alot for your help. Really appreciate it.
I have another problem here.
I need to sort TreeMap with comparator using variable which is neither
the key nor the value of treemap.
So I create a treemap and assign the comparator to it.
Coding as below:
Map attMap = new TreeMap(new Comp());
for (AttBean attribute : a.getAttributes()) {
attMap.put(attribute.getName(), attribute.getValue());
}
--Error when comes to comparator
public class Comp implements Comparator {
public int compare (Object z1, Object z2) {
//to get id based on the key passed to comparator
--error occur
AttBean ab1 = (AttBean)z1;
AttBean ab2 = (AttBean)z2;
String a = ab1.getID().toString();
// Condition for comparator
// return compare result
}
}
/********************************************************
error:
java.lang.ClassCastException: java.lang.String
com.wgc.bo.wip.Comp.compare(Comp.java:22)
java.util.TreeMap.compare(TreeMap.java:1093)
java.util.TreeMap.put(TreeMap.java:465)
com.wgc.web.action.wip.WIP.doLoadDefaultValues(WIP.java:255)
Is the AttBean I used not compatible when sorting using comparator?
Any suggestion for the problem above?
Thanks.