【发布时间】:2019-02-19 14:54:34
【问题描述】:
我正在尝试根据长度和大小写敏感度对字符串列表进行排序。
示例: 排序前:[a, abc, b, fe, e, ABC, Abc]
排序后:[a, b, e, fe, abc, Abc, ABc, ABC]
public static void main(String[] args) {
List<String> stringList = new ArrayList<>();
stringList.add("a");
stringList.add("abc");
stringList.add("b");
stringList.add("fe");
stringList.add("e");
stringList.add("ABC");
stringList.add("Abc");
stringList.add("ABc");
System.out.print("Before Sort:");
System.out.println(stringList);
Collections.sort(stringList, new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
if(o1.length() > o2.length())
{
return 1;
}
else if(o1.length() < o2.length()){
return -1;
}
else if(o1.length() == o2.length()){
return return o1.compareTo(o2);
}
else return 0;
}
});
System.out.print("After Sort :");
System.out.println(stringList);
}
以上代码根据长度对列表进行排序,但未能根据大小写敏感度排序。
它给出了输出, [a, b, e, fe, ABC, ABc, Abc, abc]
预期输出 排序后:[a, b, e, fe, abc, Abc, ABc, ABC]
感谢任何帮助。
【问题讨论】: