You can use your own comparator as follows:
Comparator<String> secondCharComparator = new Comparator<String>() { @Override public int compare(String s1, String s2) { return s1.substring(1, 2).compareTo(s2.substring(1, 2)); } };
Example:
SortedMap<String,String> map = new TreeMap<String,String>(secondCharComparator); map.put("Za", "FOO"); map.put("Ab", "BAR"); map.put("00", "ZERO"); System.out.println(map);
Note that this simply assumes that String has a character at index 1. It throws a StringIndexOutOfBoundsException if it is not.
Alternatively, you can also use this comparison:
return s1.charAt(1) - s2.charAt(1);
This subtractive βtrickβ is broken at all, but it works fine here, because subtracting two char will not overflow int .
The above solution substring and compareTo more readable.
See also:
- Java Integer: what is faster comparison or subtraction?
polygenelubricants May 01 '10 at 4:03 a.m. 2010-05-01 04:03
source share