我一直在尝试寻找可能的答案,但一无所获。
我有一个充满自定义对象的ArrayList
。它们的字段之一是 boolean 值。
我想将此对象放在第一位,保留其余元素
例如,如果我有这个列表,并且 obj5
是这个 boolean 值设置为 true 的列表:
obj3, obj2, obj5, obj7, obj9
我想得到这个:
obj5, obj3, obj2, obj7, obj9
编辑:不能使用 LAMBDAS、JAVA 6
编辑 2:请注意列表的其余部分必须保持旧顺序
编辑3:简而言之,我需要这个程序输出[B,A,C,D,E]:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Trip {
@Override
public String toString() {
return name;
}
private String name;
private boolean freeCancellation;
public Trip(String name, boolean freeCancellation) {
this.name = name;
this.freeCancellation = freeCancellation;
}
static Comparator<Trip> myOrder = new Comparator<Trip>() {
public int compare(Trip a, Trip b) {
if (a.freeCancellation == b.freeCancellation) return 0;
return a.freeCancellation ? -1 : 1;
}
};
public static void main(String [] args){
Trip t1 = new Trip("A", false);
Trip t2 = new Trip("B", true);
Trip t3 = new Trip("C", false);
Trip t4 = new Trip("D", true);
Trip t5 = new Trip("E", false);
List<Trip> tripList = new ArrayList<>();
tripList.add(t1);
tripList.add(t2);
tripList.add(t3);
tripList.add(t4);
tripList.add(t5);
System.out.println(Arrays.toString(tripList.toArray()));
Collections.sort(tripList, myOrder);
//result should be [B, A, C, D, E]
System.out.println(Arrays.toString(tripList.toArray()));
}
}
最佳答案
写一个Comparator
.
Comparator<MyType> myOrder = new Comparator<MyType>() {
public int compare(MyType a, MyType b) {
return (b.booleanField() ? 1 : 0) - (a.booleanField() ? 1 : 0);
}
}
使用此比较器进行排序。
Collections.sort(myList, myOrder);
编辑
看来您真正要求的是将仅一个匹配元素移动到列表的前面。这应该很容易。
找到要移动的元素的索引:
int foundIndex = -1;
for (int i = 0; i < tripList.size(); ++i) {
if (tripList.get(i).freeCancellation) {
foundIndex = i;
break;
}
}
如果找到这样的元素,并且它尚未位于开头,请将其移至开头:
if (foundIndex > 0) {
tripList.add(0, tripList.remove(foundIndex));
}
关于java - 仅获取 ArrayList 中符合条件的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41741425/