使用自定义Comparator在Java中创建SortedMap [英] Create a SortedMap in Java with a custom Comparator

查看:644
本文介绍了使用自定义Comparator在Java中创建SortedMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Java在自定义排序顺序中创建一个 TreeMap 。作为字符串的排序键需要根据第二个字符进行排序。这些值也是字符串。

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.

示例地图:

Za,FOO
Ab,Bar


推荐答案

你可以使用像这样的自定义比较器:

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));
        }           
    };

示例:

    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}"

注意这个简单地假设 String 在索引1处有一个字符。它抛出 StringIndexOutOfBoundsException 如果没有。

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);

这个减法技巧一般会被打破,但它在这里工作正常,因为减去两个 char 不会溢出 int

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

substring compareTo 上面的解决方案更具可读性。

The substring andcompareTo solution above is more readable, though.

  • Java Integer: what is faster comparison or subtraction?

这篇关于使用自定义Comparator在Java中创建SortedMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆