如何使用 Java 的 lambda 表达式打印数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23324782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Java's lambda expressions to print an array?
提问by Victor Lyuboslavsky
How can I achieve the following array print using Java 8's lambda expressions?
如何使用 Java 8 的 lambda 表达式实现以下数组打印?
int[] values = new int[16];
// Populate values
for (int value : values) {
System.out.println(Integer.toUnsignedString(value, 16));
}
采纳答案by JB Nizet
Arrays.stream(values)
.mapToObj(i -> Integer.toUnsignedString(i, 16))
.forEach(System.out::println);
回答by Karibasappa G C
Hi you can convert array to list and make use of lambda as below using new forEach method.
嗨,您可以使用新的 forEach 方法将数组转换为列表并使用如下所示的 lambda。
int[] values = new int[16];
List<Integer> list = Arrays.asList(values);
list.forEach(n -> System.out.println(n));
回答by Maurice Naftalin
IntStream.of(values)
.mapToObj(i -> Integer.toUnsignedString(i, 16))
.forEach(System.out::println);
is an alternative (clearer IMO) to Arrays.stream()
.
是Arrays.stream()
.
回答by sakumar
String[] nums = {"three","two","one"};
Arrays.stream(nums).forEach(num -> System.out.println(num));
回答by parasuraman s
For simply printing integer, we don't need to map to any new object
为了简单地打印整数,我们不需要映射到任何新对象
Arrays.stream(arrInt1)
.forEach(i ->{
System.out.print(i);
System.out.print("\t");
});
回答by Hetal Rachh
You can print the array in a simple way just by using one line of code instead of writing a loop, using Java8 features i.e. stream
and method
references
您可以通过使用一行代码而不是编写循环以简单的方式打印数组,使用 Java8 特性 iestream
和method
引用
Example:
例子:
int arrayName[] = new int[size];
Arrays.stream(arrayName).forEach(System.out::println); //This will iterate and print each element of the array.