New object instantiation when using Java 8 streams

Is there a differnce in using the following contstructs, other than slightly better readability in the latter? -> new NewClass(item)).collect(Collectors.toList());;


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));

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.

Need Your Help


mysql replace auto-increment load-data-infile

I am trying to load a file onto a MySQL database, having the primary key auto_incremented and I would like the data to be updated if i find any duplicate rows. However, the REPLACE keywords only wo...

AWS: Publish SNS message for Lambda function via boto3 (Python2)

python-2.7 amazon-sns aws-lambda boto3

I am trying to publish to an SNS topic which will then notify a Lambda function, as well as an SQS queue. My Lambda function does get called, but the CloudWatch logs state that my "event" object is...