gpt4 book ai didi

Java 8 原始流到集合的映射方法

转载 作者:太空宇宙 更新时间:2023-11-04 09:16:24 25 4
gpt4 key购买 nike

这两种流创建方法之间是否存在显着差异(在性能或最佳实践方面)?

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/58922783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com