Create a SortedMap in Java with a custom Comparator

瘦欲@ 提交于 2019-11-26 21:28:39

问题


I want to create a TreeMap in Java with a custom sort order. The sorted keys which are string need to be sorted according to the second character. The values are also string.

Sample map:

Za,FOO
Ab,Bar

回答1:


You can use a custom comparator like this:

    Comparator<String> secondCharComparator = new Comparator<String>() {
        @Override public int compare(String s1, String s2) {
            return s1.substring(1, 2).compareTo(s2.substring(1, 2));
        }           
    };

Sample:

    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 the String has a character at index 1. It throws StringIndexOutOfBoundsException if it doesn't.


Alternatively, you can also use this comparison:

return s1.charAt(1) - s2.charAt(1);

This subtraction "trick" is broken in general, but it works fine here because the subtraction of two char will not overflow an int.

The substring andcompareTo solution above is more readable, though.

See also:

  • Java Integer: what is faster comparison or subtraction?



回答2:


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

You could easily accomplish this by creating a "wrapper" class for String and overriding the compareTo method



来源:https://stackoverflow.com/questions/2748829/create-a-sortedmap-in-java-with-a-custom-comparator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!