Which class is that map() method defined in? There are seven map() methods in the
standard Java® API. Only five take a single parameter, and guessing that you aren't working in a stream of primitives or an Optional, that leaves one suitable method:
this one. So let's assume for the time being that I have found the method you wanted. Look at its details from the link above. Its return type is
Stream<R> which means it takes one Stream, the object on which it is called, and returns a reference to a different Stream. You can also tell that because the link calls it an
intermediate operation.
Its parameter type is
Function<? super T,? extends R> where the T is the type of elements of the “old” Stream and the R is a
result which will be the type of the “new” Stream. Now, let's look at the details of Function. For a start,
That API link wrote:Functional Interface:
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
We now know it has one abstract method and that abstract method is what you are implementing
via that λ.
This is that abstract method. You will see it takes a T as its parameter and returns an R. That determines how you have to implement it: you must supply one parameter which is the T and it must return an R. So no, you cannot implement Function#apply without returning something. This is how you might implement it as an anonymous class. Later on I shall whittle that down to a λ.
That does something simple, mapping a
String to the number of keystrokes it contains. Now let's start whittling it down. You already know it is a Function, so who needs the name of the class, or the {}?
Now, we already can guess the name of the method because we know there is only one method actually having to be implemented, so we can lose the method name and modifiers and return type:-
Now, use the -> arrow token to join the parameters to the method body:-
What you are writing is a formula to go from a String to an Integer, and you now have an expression which represents a String on the left of -> and you want to reduce what is on the right of the -> to a simple expression too, so we can get rid of {} and return and some whitespace:-
We know s is a String so we can delete String:-
Because there is only one token, s, inside the (), we can delete the ().
Now look at the difference from what you had. You aren't returning anything, so the compiler won't be happy about that. You could add
return true; to your λ, but that will produce a Stream<Boolean>, which you probably don't want. Salvin is surely correct to suggest using forEach, particularly since forEach permits side effects like writing to files.