我有一个 ArrayList<String>
在 java 。现在我想根据一些要求对其进行排序。
例如,我在 ArrayList 中有这些项目:
xyz
bcd
abc_locked
cde
efg_locked
fgh
我想用 _locked
推回那些最后并保持顺序,使这个:
xyz
bcd
cde
fgh
abc_locked
efg_locked
最好的方法是什么?我是否必须遍历列表删除字符串并再次添加它?或者有更好的方法吗?
最佳答案
你可以尝试使用这个比较器:
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String arg1, String arg2) {
if (arg1.matches("^.*_locked$") && arg2.matches("^.*_locked$")) {
// Both string have _locked at the end. Retain the order.
return 0;
} else if (arg1.matches("^.*_locked$")) {
// First string have _locked. Swap.
return 1;
} else if (arg2.matches("^.*_locked$")) {
// Second string have _locked. No need to swap
return -1;
}
// None of the string have _locked. Retain the order
return 0;
}
};
Collections.sort(list, comparator);
关于Java,对末尾较长条目的ArrayList进行特殊排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17343763/