Arrays.asList与Arrays.stream一起使用forEach() [英] Arrays.asList vs. Arrays.stream to use forEach()

查看:132
本文介绍了Arrays.asList与Arrays.stream一起使用forEach()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果你有一个数组而你想使用Java8 forEach()方法,哪种方法更好或更有效:

If you have an Array and you want to use the Java8 forEach() method, which approach is better or more efficient:

Arrays.asList(new String[]{"hallo","hi"}).forEach(System.out::println);

Arrays.stream(new String[]{"hallo","hi"}).forEach(System.out::println);

差异是显着还是有更好的解决方案可以解决这个问题?

Is the difference significant or are there any better solutions to solve this?

推荐答案

两者都没有。如果你已经有一个数组,

Neither. If you already had an array,

String[] array;

我会使用:

Arrays.stream(array).forEach(System.out::println);

因为您将数组的转换保留为JDK的流 - 让它负责效率等等。

because you leave the conversion of the array to a stream to the JDK - let it be responsible for efficiency etc.

但是,由于你没有数组,我会使用 Stream.of()' s varargs创建值的流:

But, since you don't have an array, I would use Stream.of()'s varargs to create a stream of the values:

Stream.of("hallo","hi").forEach(System.out::println);

这再次让JDK负责按照自己认为合适的方式有效地传输值。

Which again lets the JDK take the responsibility of efficiently streaming the values as it sees fit.

这篇关于Arrays.asList与Arrays.stream一起使用forEach()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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