这两种流创建方法之间是否存在显着差异(在性能或最佳实践方面)?
int[] arr2 = {1,2,3,4,5,6};
Arrays.stream(arr2)
.map((in)->in*2)
.mapToObj((in) -> new Integer(in))
.collect(Collectors.toCollection(()-> new ArrayList<>()));
Arrays.stream(arr2)
.map(in->in*2)
.boxed()
.collect(Collectors.toCollection(()-> new ArrayList<>()));
编辑
感谢 Stack Community 的回答,我可以为新读者添加一些插件来完善问题:
正如许多人指出的那样,.boxed()
IntStream 方法定义为:
@Override
public final Stream<Integer> boxed() {
return mapToObj(Integer::valueOf);
}
什么基本上重新定义了以下哪个更好的问题:
.mapToObj(in -> new Integer(in))
或
.mapToObj(in -> Integer.valueOf(in))
最佳答案
是的,boxed()
使用 Integer.valueOf
它可以从 cache 中检索一些 Integer
实例.
因此,您应该使用带有 boxed()
的版本(最好),或者使用 Integer.valueOf
而不是 new Integer()
.请注意 boxed()
实际上是 mapToObj(Integer::valueOf)
的简写.
关于Java 8 原始流到集合的映射方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53985683/