使用 Java 8 流时的新对象实例化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31763930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:35:01  来源:igfitidea点击:

New object instantiation when using Java 8 streams

javalambdajava-8java-streammethod-reference

提问by ShellDragon

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

采纳答案by Tagir Valeev

Generally there's no difference. NewClass::newproduces less bytecode as in lambda version an auto-generated private method is created by java compiler from the lambda body while NewClass:newdirectly 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.

一般没有什么区别。NewClass::new产生更少的字节码,因为在 lambda 版本中,自动生成的私有方法由 java 编译器从 lambda 主体创建,同时NewClass:new直接链接到构造函数方法句柄。因此,使用方法引用,您的类文件大小可能会稍小一些。不过,预计不会有显着的性能差异。

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:

然后你可以用 lambda 或函数接口调用它:

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::newnow matches to both constructors, while lambda is still unambiguous.

然后方法引用调用将变得不明确,并且会导致编译错误,因为NewClass::new现在与两个构造函数都匹配,而 lambda 仍然是明确的。