Vipin
Vipin

Reputation: 5223

Lambda expression coding variation for optional.filter

I am trying to experiment with lambda expressions, is there any other way we can write filter ( optional.filter(s -> (s.length() > 4)) )

This is complete working code:

public class Main {
    public static void main(String[] args) {

        Optional<String> optional = Optional.of("Hello");

        System.out.println(optional.filter(s -> (s.length() > 4)).get());
    }
}

For example one wrong way is below, though it throws compilation saying "can not resolve method length" but here with this trying to explain kind of variation I am thinking.

optional.filter(length() > 4)

Upvotes: 0

Views: 67

Answers (2)

Pankaj Singhal
Pankaj Singhal

Reputation: 16053

If you don't want to write complex operations in the stream chain, you can always define the Function / Predicate / etc separately and just use them. It also increases readability.

For example, you can define a Predicate for you case like below:

Predicate<String> byStrLengthCheck = s -> s.length() > 4;

And use the above Predicate like below:

System.out.println(optional.filter(byStrLengthCheck).get());

Upvotes: 0

Ousmane D.
Ousmane D.

Reputation: 56453

You're trying to introduce syntax that is not allowed in java.

These are the valid syntax:

optional.filter(s -> s.length() > 4)

or:

optional.filter(s -> {
     return s.length() > 4;
})

or:

optional.filter(new Predicate<String>() {
        @Override
        public boolean test(String s) {
            return s.length() > 4
        }
})

You should prefer the first in this specific case as it's more compact and readable.

Upvotes: 1

Related Questions