简体   繁体   中英

Apply Filter if given value is not null

I have a list of student objects. I want to filter this list based on some parameter using java 8. My code is like that

studentName = "test";

studentsList = students.stream().filter(s -> s.getName().equals(studentName )).collect(Collectors.toList());

But I want to apply this filter if studentName is not null. If studentName is null then I don't want this filter work. Can I make this studentName as optional in filter?

Either do it in two steps:

Stream<Student> studentStream = students.stream();
if (studentName != null) {
    studentStream = studentStream.filter(s -> s.getName().equals(studentName));
}
studentsList = studentStream.collect(Collectors.toList());

Or add the null check into the filter itself:

studentsList = students.stream()
        .filter(s -> studentName == null || s.getName().equals(studentName))
        .collect(Collectors.toList());

I had similar doubts about how to perform this operation. Here is a clear answer with an example for it. I have a class called Employee which has id, name and department in it. And List of Employee and I want to filter those where employee list is not null and
its department is 'management' Something like this

Employee e1=new Employee();
    e1.setId("1");
    e1.setName("abc");
    e1.setDept("finance");
    Employee e2=new Employee();
    e2.setId("2");
    e2.setName("mno");
    e2.setDept(null);       
    Employee e3=new Employee();
    e3.setId("3");
    e3.setName("pqr");
    e3.setDept(null);
    Employee e4=new Employee();
    e4.setId("3");
    e4.setName("ghi");
    e4.setDept("management");
    
    List<Employee> list=new ArrayList();
    list.add(e1);
    list.add(e4);
    list.add(e3);
    list.add(e2);
    list=list.stream().filter(e->e.getDept()!=null && e.getDept().equals("management")).collect(Collectors.toList());// This will filter the list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM