Create a SortedMap in Java with a special Comparator

I want to create a TreeMap in Java with a custom sort order. Sorted keys, which are strings, must be sorted according to the second character. Values ​​are also strings.

Map example:

 Za,FOO Ab,Bar 
+16
java string sorting treemap comparator
May 01 '10 at 3:56
source share
2 answers

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); // prints "{00=ZERO, Za=FOO, Ab=BAR}" 

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?
+25
May 01 '10 at 4:03
source share

Assuming you don't mean Hash, as in a hash function or sort ...

You can easily do this by creating a wrapper class for String and overriding the compareTo method

0
May 01 '10 at 5:34
source share



All Articles