java8stream操作:从集合中获取符合条件的元素
List<Student> students = new ArrayList<>();
students.add(new Student(1,"张三",90));
students.add(new Student(2,"李四",60));
students.add(new Student(3,"王五",30));
students.add(new Student(4,"赵六",85));
int studentId = 3;
Student student = students.stream().filter(o -> o.getId() == studentId).findAny().orElse(null);
如上,获取id为3的元素对象,如果不存在返回null。
student类:
public class Student {
private int id;
private String name;
private int score;
public Student(int id, String name, int score) {
this.id = id;
this.name = name;
this.score = score;
}
get...
set...
}
其他用法:
List<WorkHandoverModel>workHandoverList2=workHandoverList.stream().filter(item->item.getIsDelete().equals(0)).collect(Collectors.toList());//获取list中符合没有删除的工作交接的list
List<WorkHandoverModel>workHandoverList1=workHandoverList.stream().filter(item->item.getIsDelete().equals(1)).collect(Collectors.toList());
workHandoverList1.stream().forEach(item->item.setDispathStatus(null));//对查询出来的list统一赋值
workHandoverList1.stream().forEach(item->item.setShowDispathStatus(null));
//workHandoverList1.stream().forEach(item->item.setDispathId(null));
workHandoverList2.addAll(workHandoverList1);