sta*_*man 0 java collections arraylist
我一直试图找到可能的答案,但没有发现.
我有ArrayList一整套自定义对象.他们的一个领域是boolean.
我想把这个对象放在第一位,保留其余的元素
例如,如果我有这个列表并且obj5是将此布尔值设置为true的那个:
obj3, obj2, obj5, obj7, obj9
Run Code Online (Sandbox Code Playgroud)
我想得到这个:
obj5, obj3, obj2, obj7, obj9
Run Code Online (Sandbox Code Playgroud)
编辑:不能使用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()));
}
}
Run Code Online (Sandbox Code Playgroud)
写一个Comparator.
Comparator<MyType> myOrder = new Comparator<MyType>() {
public int compare(MyType a, MyType b) {
return (b.booleanField() ? 1 : 0) - (a.booleanField() ? 1 : 0);
}
}
Run Code Online (Sandbox Code Playgroud)
使用此比较器排序.
Collections.sort(myList, myOrder);
Run Code Online (Sandbox Code Playgroud)
因此,您实际要求的似乎是将一个匹配元素移动到列表的前面.这应该很容易.
找到要移动的元素的索引:
int foundIndex = -1;
for (int i = 0; i < tripList.size(); ++i) {
if (tripList.get(i).freeCancellation) {
foundIndex = i;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您找到这样的元素,并且它尚未在开头,请将其移至开头:
if (foundIndex > 0) {
tripList.add(0, tripList.remove(foundIndex));
}
Run Code Online (Sandbox Code Playgroud)