我想对包含许多行的arraylist进行排序
我想忽略 ' - '
if it is the first letter of that line
INPUT
-bbb
A-AAA
滴滴滴
B-DDD
C-CCC
output
should be (as u can see it should be sorted on first character(a b c d )
A-AAA
-bbb
C-CCC
滴滴滴
E-EEE
here is the code i have
Collections.sort(arrList, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.startsWith("-") && o2.startsWith("-")) {
return compare(o1.substring(1), o2.substring(1));
}
if (o1.startsWith("-")) {
return 1;
}
if (o2.startsWith("-")) {
return -1;
}
return o1.compareTo(o2);
}
});
4 回答
或者,更短但可读性更低
你用|在比较器而不是 - .
您的比较不正确,如果
o1
以-
开头,则不能忽略o2
:这将忽略许多结果....
To compare correctly you must follow this behaviour :如果
String
以-
开头,则获得第二个字符(位置1),否则取第一个字符(位置0) . 只要你不能compareTo
原始类型,substring
的单个字符会更有用 .分别为每个字符串执行此操作,并为结果执行
compareTo
.知道了这一点,你可以实现你的比较器(还有其他的减少和oneliners答案,但为了OP可以更好地理解我将是基本的):
Main for test:
Output:
老实说,没有必要做那么多工作 . 只需在使用正则表达式时比较两个值 . 你最初遇到的问题是,当他们以
-
开头时,你从来没有忽略过它们,如果它确实以-
开头,你只是比另一个更大了一个lexograhpplyO / P
这是您的要求的逻辑