Is there a differnce in using the following contstructs, other than slightly better readability in the latter?
someList.stream().map(item -> new NewClass(item)).collect(Collectors.toList()); someList.stream().map(NewClass::new).collect(Collectors.toList());
Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
Generally there's no difference. NewClass::new
produces less bytecode as in lambda version an auto-generated private method is created by java compiler from the lambda body while NewClass:new
directly links to the constructor method handle. So using method references you may have slightly less class file size. No significant performance difference is expected though.
Another difference is method resolution procedure. It's not applicable in your particular example, but may be applicable in other code. For example, you have two constructors:
public NewClass(String a) {...} public NewClass(String a, String b) {...}
And you have some method which accepts functional interface:
public myMethod(Function<String, NewClass> fn) {...}
Then you can call it both with lambda or functional interface:
myMethod(str -> new NewClass(str)); myMethod(NewClass::new);
But suppose that later you add a new method with the same name like this:
public myMethod(BiFunction<String, String, NewClass> fn) {...}
Then method reference call will become ambiguous and will result in compilation error as NewClass::new
now matches to both constructors, while lambda is still unambiguous.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With