1

I am new to lambda expressions. I have the below code:

List<String> someNumbers = Arrays.asList("N40", "N36", "B12", "B6", "G53", "G49", "G60", "G50", "G53", "I26", "I17", "I29", "O71");

someNumbers
            .stream()
            .filter(startsWith("G"))

In the above code, the 'filter' should act as a predicate and return a boolean value. But why does it show a compile error? I don't get an error when I use the below line:

.filter(s->s.startsWith("G"))

Above, the stream get passed to the filter. so what is the need for the argument s? for instance, '.map' processes it without any errors if used as

.map(String::toUppercase).
1
  • 1
    Please take a close look to the Java Tutorial, Lambda Expressions Section. In every programming language, you have to respect the syntactic rules. Commented Aug 31, 2018 at 16:22

1 Answer 1

3

basic knowledge on method references I guess.

String::toUppercase

is equivalent to:

s -> s.toUppercase()

While:

startsWith("G")

would theoretically be equivalent to:

s -> s.startsWith("G")

This is simply not allowed by the language.

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

1 Comment

Well, instead of saying “this is simply not allowed by the language” it would make more sense to say that startsWith("G") already has a meaning in the Java language, i.e. “invoke this method right at this point and use the return value”, for 25 years now and changing it to “do not invoke this method but create a predicate instance at this point which may invoke this method” would be a very disruptive change. What about code which actually want to invoke a method and use the returned predicate?

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.