4

I am working with java-8. Please 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 perform 2 check -

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

and

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

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

dept.getCode().equals("CS");

3 Answers 3

10

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");
                    })
            .collect(Collectors.toList());  

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@Razib Yes. Because Predicate is a functional interface with an abstract method with the signature boolean test(T t). This is the method you are implementing as a lambda. So in order to satisfy this interface, you have to return a boolean. See docs.oracle.com/javase/8/docs/api/java/util/function/…
5

An alternative is

studentsOfThisDept = students.stream()
    .filter(Objects::nonNull)
    .filter(s -> Optional.ofNullable(s.getDepartment())
                         .map(Department::getCode).filter(c -> c.equals("CS")).isPresent()
           )
    .collect(Collectors.toList());

Comments

2
studentsOfThisDept = students.stream()
            .filter(s -> {
                    if (s == null) return false;
                    Department dep = s.getDepartment();
                    return (dep != null && dep.getCode().equals("CS")
                    );})
            .collect(Collectors.toList()); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.