Storing some value in a variable when using lambda expression

I work with java-8. See the following code snippet -

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

Here I have to do 2 check -

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

and

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

Is there a way to save the value s.getDepartment()for some variable (e.g. dept) so that in the second check I could write -

dept.getCode().equals("CS");
+4
source share
3 answers

Enter a variable after filtering zero students

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

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

+10
source

studentsOfThisDept = students.stream()
    .filter(Objects::nonNull)
    .filter(s -> Optional.ofNullable(s.getDepartment())
                         .map(Department::getCode).filter(c -> c.equals("CS")).isPresent()
           )
    .collect(Collectors.toList());
+5
studentsOfThisDept = students.stream()
            .filter(s -> {
                    if (s == null) return false;
                    Department dep = s.getDepartment();
                    return (dep != null && dep.getCode().equals("CS")
                    );})
            .collect(Collectors.toList()); 
+2

Source: https://habr.com/ru/post/1658672/


All Articles