New object instantiation when using Java 8 streams

JavaLambdaJava 8Java StreamMethod Reference

Java Problem Overview


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 Solutions


Solution 1 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShellDragonView Question on Stackoverflow
Solution 1 - JavaTagir ValeevView Answer on Stackoverflow