'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?
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Azim Uddin |