[英]Create a SortedMap in Java with a custom Comparator
I want to create a TreeMap
in Java with a custom sort order. 我想用Java自定义排序顺序创建一个TreeMap
。 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
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. 请注意,这只是假设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 char
will not overflow an int
. 这个减法“技巧”一般都被打破了,但它在这里运行正常,因为两个char
的减法不会溢出一个int
。
The substring
and compareTo
solution above is more readable, though. 但是,上面的substring
和compareTo
解决方案更具可读性。
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方法来轻松完成此操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.