It the
Function interface had been introduced in Java7, you would have to instantiate it like this:-
or like this:-
...and you can use it (named class version) in code like this:-
...where
f is an instance of
Foo. We should all be familiar with that sort of code. In Java8 the compiler was enhanced to infer most of the content of that sort of code. Let's see how much we can leave out, starting with the anonymous class version in full. You have a
Stream<Foo>, which means it will pass a reference to a
Foo instance to whatever comes next, and this code will return a reference to a
Stream<Bar>:-
Now, you need to work out what the compiler “knows” about that anonymous class. It knows it has to be a
Function<T, R> because that is what the method takes as its argument. So we can remove the interface name and one pair of {} delimiting the class:-
It also “knows” that Function has one abstract method and one only which makes it a
FunctionalInterface; it even says so in the documentation link I posted earlier. So who needs the method name, or return type because you can infer it is
Bar apply?
You no longer need the {} as long as you remove
return, but you do need to add an arrow token:-
In 90%+ of cases, it is possible to infer the type of the argument from the type of the preceding Stream, so we can presume it is a
Foo, which means we can delete the type: we can also remove the () because they would now contain one token and () are redundant around a single token:-
At which point you have the shortest λ you can get. But what are you doing with
f? Nothing. You are simply passing it to a constructor call and the constructor may do something with it. So you have a shorthand (details in the
Java™ Tutorials) for
Take that one reference and pass it to this method or constructor
What you do is write the name of an object or a class, double colon and the name of the method. Since constructors aren't methods, you can't give them a method name. But a constructor is called by means of the
new keyword or operator, so they reused
new.
And that is what Rob told you about.