I want to make a TreeMap, so that each time an entry is inserted in the TreeMap - the entry is sorted based on value on the run. (needs O(logN) time.) So, I define a TreeMap with its constructor like below :: I dont understand where is the problem... i am confused. Can anyone please explain me the error/problem ?
Code ::
Map<String,Integer> tm =
new TreeMap<String,Integer>(new Comparator<Map.Entry<String,Integer>>(){
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
throw new UnsupportedOperationException("Not supported yet."); // implement logic here
}
});
The comparator is for the key
Map<String,Integer> tm =
new TreeMap<String,Integer>(new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
throw new UnsupportedOperationException("Not supported yet."); // implement logic here
}
});
You should sort entries based on the entry's key. So comparator should compare two strings here. (new Comparator(){...}) as suggested in other answer here.
Take a look at constructor documentation: http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html#TreeMap(java.util.Comparator)
If you really need to sort by the value, you should create a new object for the key, also containing your value:
class MyKey {
String str;
Integer i;
...
}
Map<MyKey,Integer> tm = new TreeMap<MyKey, Integer>(new Comparator<MyKey>(){
@Override
public int compare(MyKey o1, MyKey o2) {
String str1 = o1.str;
String str2 = o2.str;
// implement logic here
}
};
You need to provide comparator, which compares keys, rather then full map entries. So to create TreeMap<String,X>
( X
is any type) you need to provide Comparator<String>
. This can be done like this:
Map<String,Integer> tm = new TreeMap<String,Integer>(new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
// implement logic here
// sample implementation below
return o1.comparateTo(o2)
}
});
If natural ordering of strings (see: javadoc for String#compareTo) is fine for you, you can just write:
Map<String,Integer> tm = new TreeMap<String,Integer>();
Notice that in both cases, ordering of keys is the same. In both cases String#compareTo
method is used to compare keys. Only in the first example we are providing comparator explicitly and in the second one we using the fact that String
implements Comparable
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.