我想为字符串值创建一个比较器,但根据 https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html下划线符号比任何数字都具有更大的值(value)。有可能以某种方式改变它吗?
最佳答案
简短回答
是的,确实如此。您需要一个自定义字符串比较器。
解决方案
假设您需要对字符串列表进行排序:
[a_123, ab123, a123, 123, _123]
如果您使用Collections.sort
对其进行排序,那么它将按以下顺序排序:
[123, _123, a123, a_123, ab123]
但是您想覆盖 _
的“权重”。为了实现这一点,您需要一个自定义字符串比较器。让我们复制并修改一下java.lang.String#compareTo
:
private int customStringComparator(String s1, String s2) {
int len1 = s1.length();
int len2 = s2.length();
int lim = Math.min(len1, len2);
char v1[] = s1.toCharArray();
char v2[] = s2.toCharArray();
int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
// You can add your custom comparison here:
if ('_' == c1 && Character.isDigit(c2)) {
// We intentionally return inverted result
return c2 - c1;
}else if(c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}
现在我们可以将 customStringComparator
传递给 Collections.sort
:
Collections.sort(list, this::customStringComparator);
列表将按以下顺序排序:
[_123, 123, a_123, a123, ab123]
如您所见,现在 _
位于数字之前。
关于java - 是否可以更改排序中某些符号的优先级(权重)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53150521/