It might be easier to understand if you separate the code a little more:
public interface MyStream<T> {
Stream<T> stream();
}
class Util {
static <T> MyStream<T> of(Stream<T> stream) {
return () -> stream;
}
}
It is still doing the same thing, but it is a little easier to follow.
Then in a second step, let's write this without a lamda expression in the "classic" way:
public interface MyStream<T> {
Stream<T> stream();
}
class Util {
static <T> MyStream<T> of(Stream<T> stream) {
return new MyStream<>() {
Stream<T> stream() {
return stream;
}
};
}
}
What you are doing here is create an anonymous class, that implements the interaface MyStream
. It has a method stream
which returns the stream
you passed as method argument.
Now with Java 8 there is this fancy new format to write things. This is possible if the interface has only a single method. In this case the new Stream
is not necessary, because the compiler knows the type from the return type of your method. Also the Stream<T> stream()
definition is not necessary, because the compiler knows it from the interface definition. And in case of a single statement, you can even omit the return
, because the compile will assume the result of the single statement to be the return-value.
Thus this:
return new MyStream<>() {
Stream<T> stream() {
return stream;
}
};
can be written as:
() -> stream;
// ^^^^^^^ Return value
//^^ Argument list (in this case empty)