java8 stream: Obtain the qualifying element from the collection

java8stream: Obtain the qualifying element from the collection

    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);


As described above, obtaining an id of the object 3, if there is no return null.

student categories:
 

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...
}

Other uses:

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);
Published 48 original articles · won praise 26 · views 70000 +

Guess you like

Origin blog.csdn.net/qq_38316721/article/details/103879737