java 8 二次排序,和空指针处理示例

public class MainTest {
public static void main(String[] args) {
List<DoubleSort> list = new ArrayList<DoubleSort>();
list.add(new DoubleSort(0, "1"));
list.add(new DoubleSort(3, "2"));
list.add(new DoubleSort(2, "22"));
list.add(new DoubleSort(3, "11"));
list.add(new DoubleSort(3, "222"));
// 简单排序
list.sort(Comparator.comparing(DoubleSort::getId));
// 二次排序
list.sort(Comparator.comparing(DoubleSort::getId).thenComparing(DoubleSort::getName));
list.add(new DoubleSort(3, null));
// 空指针处理空值放到前面
list.sort(Comparator.comparing(DoubleSort::getName, Comparator.nullsFirst(Comparator.naturalOrder())));
list.forEach(e -> System.out.println(e.getId() + "," + e.getName()));
}
}



public class DoubleSort {
int id;
String name;
public DoubleSort(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

猜你喜欢

转载自blog.csdn.net/york_2016/article/details/80169467