我在Java中有一个ArrayList<String>
。现在我想用一些要求对它进行排序。
我在ArrayList中有这些项目,例如:
xyz
bcd
abc_locked
cde
efg_locked
fgh
我想在最后用_locked
推回那些并保留订单,以便做到这一点:
xyz
bcd
cde
fgh
abc_locked
efg_locked
最好的方法是什么?我是否必须遍历List才能删除String并再次添加它?还是有更好的方法?
答案 0 :(得分:5)
您可以尝试使用此比较器:
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);
答案 1 :(得分:1)
使用比较器:
Collections.sort(list, new Comparator(){
public int compare(String o1, String o2) {
if ((o1.endsWith("_locked")&&(!o2.endsWith("_locked"))){
return 1;
}
else if (!(o1.endsWith("_locked")&&(o2.endsWith("_locked"))){
return 1;
}
else {
//Fallback sorting based on start of string left as exercise to reader
}
}
});
答案 2 :(得分:1)
您可以尝试使用匿名参数化比较器,如下所示:
ArrayList<String> myList = new ArrayList<String>();
myList.add("xyz");
myList.add("bcd");
myList.add("abc_locked");
myList.add("cde");
myList.add("efg_locked");
myList.add("fgh");
Collections.sort(myList, new Comparator<String>() {
@Override
public int compare(String arg0, String arg1) {
if (!arg0.contains("_locked") && !arg1.contains("_locked")) {
return arg0.compareTo(arg1);
}
else if (arg0.contains("_locked") && arg1.contains("_locked")) {
return arg0.compareTo(arg1);
}
else if (arg0.contains("_locked")) {
return 1;
}
else {
return -1;
}
};
});
System.out.println(myList);
输出:
[bcd, cde, fgh, xyz, abc_locked, efg_locked]
答案 3 :(得分:1)
Comparator<String> comparator = new Comparator<String>() {
@Override
public int compare(String arg1, String arg2) {
if (arg1.endsWith("_locked") && arg2.endsWith("_locked")) {
return 0;
} else if (arg1.endsWith("_locked")) {
return 1;
} else if (arg2.endsWith("_locked")) {
return -1;
}
return 0;
}
};
答案 4 :(得分:-1)
你可以试试这个
Collections.sort(list, new Comparator() {
@Override
public int compare(String s1, String s2) {
// ascending order
return id1.compareTo(id2);
// descending order
//return id2.compareTo(id1);
}
});
对象集合
/*
Here myItems is an arraylist MyItem added randomly
MyItem got a property int id
This method provide me myItems in ascending order of id's
*/
Collections.sort(myItems, new Comparator<MyItem>() {
@Override
public int compare(MyItem lhs, MyItem rhs) {
// TODO Auto-generated method stub
int lhsId = lhs.getId();
int rhsId = rhs.getId();
return lhsId>rhsId ? 1 : -1;
}
});
当然,您可以参考this