查询到的数据放入List中,
T为实体类,假设有两个字段A和B
当 A==1时将其排序靠前,并按照B字段排序
也就说,A==1的数据,要在A!=1的数据前面,
A==1的数据还要再根据B字段排序,请不吝赐教。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Untitled {
public static void main(String[] args) {
List<I> list = new ArrayList<I>();
list.add(new I(1, 3));
list.add(new I(1, 2));
list.add(new I(1, 5));
list.add(new I(0, 5));
list.add(new I(7, 1));
list.add(new I(8, 0));
list.add(new I(9, 3));
list.add(new I(4, 9));
list.add(new I(5, 5));
Collections.sort(list, new Comparator<I>() {
@Override
public int compare(I o1, I o2) {
if (o1.A == 1 && o2.A == 1)
return o1.B - o2.B;
if (o1.A == 1 || o2.A == 1)
return o1.A == 1 ? -1 : 1;
return o1.B - o2.B;
}
});
System.out.println(list);
}
}
class I
{
public int A;
public int B;
public I(int a, int b) { A = a; B = b; }
@Override
public String toString() {
return A + "," + B;
}
}
运行结果
[1,2, 1,3, 1,5, 8,0, 7,1, 9,3, 0,5, 5,5, 4,9]