Razib Razib - 1 year ago 79
Java Question

Storing some value in variable while using lambda expression

I am working with

. Please see the following code snippet -

studentsOfThisDept = students.stream()
.filter(s -> (student != null
&& s.getDepartment() != null
&& s.getDepartment().getCode().equals("CS")

Here I have to perform 2 check -

s.getDepartment() != null ; // 1st check


s.getDepartment().getCode().equals("CS") // 2nd check

Is there any way that I can store the value of
to some variable (say
) so that in second check I can write -


Answer Source

Introduce a variable after filtering null students

studentsOfThisDept = students.stream()
            .filter(s -> s != null)
            .filter(s -> {
                     Dept dept = s.getDepartment();
                     return dept != null && dept.getCode().equals("CS");

filter() takes a predicate, which means the lambda block can do things like declare variables, log stuff etc. Just make sure to return a boolean at the end of the block. A predicate is a function that takes an object and returns boolean.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download