我有一个名称和id的ArrayList。
list.add(new Model2(null, "name1"));
list.add(new Model2("13", "name2"));
list.add(new Model2(null, "name1"));
list.add(new Model2("13", "name4"));
list.add(new Model2(null, "name1"));
list.add(new Model2("13", "name6"));
首先,如果id为null,则为
//the result should by like this:
//1. null , name1
//2. null , name1
//3. null , name1
//4. 13,name2
//5. 13,name4
//6. 13,name6
我知道如何对空值进行排序:
Collections.sort(list,sorting());
public static Comparator<? super Model2> sorting() {
Comparator<Model2> sortedList = new Comparator<Model2>() {
@Override
public int compare(Model2 o1, Model2 o2) {
return o1.getId() == null ? -1 : 0;
}
};
return sortedList;
}
但名称值怎么样?
答案 0 :(得分:1)
答案 1 :(得分:0)
List<Model2> list = new ArrayList<Model2>();
list.add(new Model2(null, "name1"));
list.add(new Model2("13", "name2"));
list.add(new Model2(null, "name3"));
list.add(new Model2(null, "name2"));
list.add(new Model2("13", "name6"));
list.add(new Model2("14", "name7"));
list.add(new Model2("13", "name4"));
list.add(new Model2("14", "name3"));
Collections.sort(list, new Comparator<Model2>() {
@Override
public int compare(Model2 o1, Model2 o2) {
if (o1.getId() != null && o2.getId() != null) {
if (o1.getId().equals(o2.getId())) {
return o1.getName().compareTo(o2.getName());
}
return o1.getId().compareTo(o2.getId());
} else if (o1.getId() == null) {
if (o2.getId() == null) {
return o1.getName().compareTo(o2.getName());
}
return -1;
} else if (o2.getId() == null) {
if (o1.getId() == null) {
return o1.getName().compareTo(o2.getName());
}
}
return 0;
}
});
for (Model2 model2 : list) {
System.out.println(model2);
}
}
给出
Model2 [id=null, name=name1]
Model2 [id=null, name=name2]
Model2 [id=null, name=name3]
Model2 [id=13, name=name2]
Model2 [id=13, name=name4]
Model2 [id=13, name=name6]
Model2 [id=14, name=name3]
Model2 [id=14, name=name7]