我一直试图将字符串分组,忽略List中存在的情况,并尝试使用区分大小写再次对它们进行排序。
所以,如果我输入如下:
"Abc","DEF","abc","dEf"
然后我的输出应该排序两次作为第一级排序使用Comparator应该是:
"Abc","abc","DEF","dEf"
和第二级排序应该是:
"abc","Abc","dEf","DEF"
我的代码如下,其中只包含单个Comparator。我们可以使用多个比较器实现这样的排序,还是调整单个比较器来实现这样的逻辑?
public class ListSortIgnoreCaseComparator {
/**
* @param args
*/
public static void main(String[] args) {
List<String> input = new ArrayList<>();
input.add("Abc");
input.add("DEF");
input.add("abc");
input.add("dEf");
System.out.println("Input: "+input);
Collections.sort(input, new GroupIgnoreCase());
System.out.println("Output: "+input);
}
}
/**
*
* @author
*
*/
class GroupIgnoreCase implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
return s1.compareToIgnoreCase(s2);
}
}
/**
*
* @author
*
*/
class SortIgnoreCase implements Comparator<String> {
@Override
public int compare(String s3, String s4) {
if(s3.equalsIgnoreCase(s4)){
return s3.compareTo(s4);
}
return 0;
}
}
输出如下:
Input: [Abc, DEF, abc, dEf]
Output: [Abc, abc, DEF, dEf]
我们可以调整比较器,使输出为:
Output: [abc, Abc, dEf, DEF]
而不是上面?
答案 0 :(得分:4)
是的,你可以比较它们忽略这种情况,只有它们相等,你才应该再次比较它们,这次不要忽视这种情况:
@Override
public int compare(String s1, String s2) {
int cmp = s1.compareToIgnoreCase(s2);
if (cmp == 0)
cmp = s1.compareTo(s2);
return cmp;
}
答案 1 :(得分:2)
public class ListSortIgnoreCaseComparator {
/**
* @param args
*/
public static void main(String[] args) {
List<String> input = new ArrayList<>();
input.add("Abc");
input.add("DEF");
input.add("abc");
input.add("dEf");
System.out.println("Input: "+input);
Collator c = Collator.getInstance();
c.setStrength(Collator.TERTIARY);
Collections.sort(input, c);
System.out.println("Output: "+input);
}
}
进一步阅读:Comparing Strings (The Java™ Tutorials > Internationalization > Working with Text)
答案 2 :(得分:1)
这是我的解决方案:
@Override
public int compare(String s1, String s2) {
int comVal = s1.compareToIgnoreCase(s2);
if (comVal == 0) {
return s2.compareTo(s1);
} else {
return comVal;
}
}
Input: [Abc, DEF, abc, dEf]
Output: [abc, Abc, dEf, DEF]