如何用java a-z或日期或从大到小或从大到小等的任何内容对List<>
进行排序?
我对此进行了很多搜索,发现Collections
仅按a-z排序,但它首先对大写字母进行排序,然后对小写字母进行排序
例如:
// Must be like this
Best
best
Book
Bus
// But it's returns this
Best
Book
Bus
best
而且速度非常慢,我看到其他应用程序会在5秒钟内加载排序列表。我的需要15或20秒!
代码:
Collections.sort(posts, new Comparator<Post>() {
@Override
public int compare(Post lhs, Post rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
最佳答案
使用String.toLowerCase()
处理单词大写的问题:
Collections.sort(posts, new Comparator<Post>() {
@Override
public int compare(Post lhs, Post rhs) {
String left = lhs.getName().toLowerCase();
String right = rhs.getName().toLowerCase();
if (left.equals(right)) {
return lhs.getName().compareTo(rhs.getName());
}
else {
return left.compareTo(right);
}
});
如果您还希望在排序中包括大小和日期之类的内容,则可以修改
compare()
方法以将它们考虑在内。例如,要按名称(第一个)和大小(第二个)进行比较,请使用以下代码:Collections.sort(posts, new Comparator<Post>() {
@Override
public int compare(Post lhs, Post rhs) {
int nameComp = lhs.getName().compareToIgnoreCase(rhs.getName());
if (nameComp == 0) {
Integer lhsSize = lhs.getSize();
Integer rhsSize = rhs.getSize();
return lhsSize.compareTo(rhsSize);
}
else {
return nameComp;
}
}
});