i have a hashmap like this:
HashMap<String,Integer> map = new HashMap<String,Integer>();
map.put("java",4);
map.put("go",2);
map.put("objective-c",11);
map.put("c#",2);
now i want to sort this map by its key length, if two keys length are equal (e.g go and c# both length 2), then sorted by alphba order. so the outcome i expect to get is something like:
printed result: objective-c, 11 java, 4 c#, 2 go, 2
here is my own attamp, but it doesnt work at all...
HashMap<String,Integer> map = new HashMap<String,Integer>();
map.put("java",4);
map.put("go",2);
map.put("objective-c",11);
map.put("c#",2);
Map<String,Integer> treeMap = new TreeMap<String, Integer>(
new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
return s1.length().compareTo(s2.length());
}
}
);
actually the 'compareTo' method appears as red (not be able to compile).... please someone help me with some code example...i am a bit confusing with how to use comparator class to customize compare object...
because
length()
doesn't definecompareTo
method thats why you see error. To correct it useInteger.compare(s1.length(), s2.length());
updated code belowThe compiler is complaining because you cannot call
compareTo
on anint
. The correct way to sort the map is the following:The first two conditions compare the lengths of the two
String
s and return a positive or a negative number accordingly. The third condition would compare theString
s lexicographically if their lengths are equal.The Comparator should be:
Explantion: Define a
Comaprator
, and next step, define a list so we can add all map entries into a list. At the end, sort the list by definedComaprator
Code:
Output:
Note: get sorted by number
if there is need to do comparison based on key, the following line can be used.
You call
String#length()
, which returns a primitiveint
. You need the static methodInteger.compare(int,int)
. If you are on Java 8, you can save yourself a lot of typing: