Java 8基本流到集合的映射方法 [英] Java 8 primitive stream to collection mapping methods

查看:88
本文介绍了Java 8基本流到集合的映射方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there any significant difference (in performance or best practices) between those two stream creation methods?

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社区的答案,我可以为新读者添加一些附加内容来质疑其完整性:

EDIT

Thanks to Stack Community answers I can add some addons to question completeness for new readers:

正如许多人指出的那样,.boxed() IntStream方法定义为:

As many pointed out, .boxed() IntStream method is defined as:

@Override
    public final Stream<Integer> boxed() {
        return mapToObj(Integer::valueOf);
    }

基本上重新定义了以下哪个更好的问题:

What basically re-defines issue to which one of following is better:

.mapToObj(in -> new Integer(in))

.mapToObj(in -> Integer.valueOf(in))

推荐答案

是的,因此,您应该使用带有boxed()的版本(最好),或者使用Integer.valueOf而不是new Integer().请注意,boxed()实际上是

So you should either use the version with boxed() (preferably), or use Integer.valueOf instead of new Integer(). Note that boxed() is in fact shorthand for mapToObj(Integer::valueOf).

这篇关于Java 8基本流到集合的映射方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆