can we use tree map with custom comparator of java.util package?
eg:
TreeMap<Integer,Node> hmap=new TreeMap<Node,Integer>(new myComparator());
But this is govong me error
can we use tree map with custom comparator of java.util package?
eg:
TreeMap<Integer,Node> hmap=new TreeMap<Node,Integer>(new myComparator());
But this is govong me error
Hy Vidushi , The TreeMap in java uses custom comparator to sort the Map by Key and not Value.
But if you want to sort a map by the value, still we have a solution using LinkedHashMap
You have to update the syntax like this to avoid the error
TreeMap<Node,Integer> hmap=new TreeMap<Node,Integer>(new myComparator());
no no that I have done but it is still giving error
public class Solution {
public static void main(String[] args) {
TreeMap<Node,Integer> hmap=new TreeMap<Node,Integer>(new myComparator());
}
}
class myComparator implements Comparator<Node>{
@Override
public int compare(Node e1, Node e2) {
return e1.value.compareTo(e2.value);
}
}
class Node{
public String value;
public int S;
}
You can refer this code