Arrays.asList vs. Arrays.stream to use forEach()(Arrays.asList 与 Arrays.stream 使用 forEach())
问题描述
如果你有一个 Array 并且你想使用 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()
的可变参数来创建值流:
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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Arrays.asList 与 Arrays.stream 使用 forEach()
- 转换 ldap 日期 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 获取数字的最后一位 2022-01-01