使用自定义比较器在 Java 中创建 SortedMap

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2748829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:24:55  来源:igfitidea点击:

Create a SortedMap in Java with a custom Comparator

javastringsortingcomparatortreemap

提问by unj2

I want to create a TreeMapin 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.

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

Sample map:

示例地图:

Za,FOO
Ab,Bar

采纳答案by polygenelubricants

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 Stringhas a character at index 1. It throws StringIndexOutOfBoundsExceptionif it doesn't.

请注意,这只是假设String在索引 1 处有一个字符。StringIndexOutOfBoundsException如果没有,它会抛出。



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 charwill not overflow an int.

这个减法“技巧”通常被打破,但它在这里工作正常,因为两个的减法char不会溢出int.

The substringandcompareTosolution above is more readable, though.

不过substringcompareTo上面的和解决方案更具可读性。

See also:

也可以看看:

回答by CheesePls

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

您可以通过为 String 创建一个“包装器”类并覆盖 compareTo 方法来轻松完成此操作