灌装使用流多维数组 [英] Filling a Multidimensional Array using a Stream
问题描述
我是新来的Java 8,目前未能充分掌握数据流,将有可能填补使用Stream功能操作数组?这是我将如何与循环标准做一个例子code:
I'm new to Java 8 and currently failing to grasp Streams fully, is it possible to fill an array using the Stream functional operations? This is an example code of how I would do it with a standard for loop:
public static void testForLoop(){
String[][] array = new String[3][3];
for (int x = 0; x < array.length; x++){
for (int y = 0; y < array[x].length; y++){
array[x][y] = String.format("%c%c", letter(x), letter(y));
}
}
}
public static char letter(int i){
return letters.charAt(i);
}
如果有可能的话用流会怎么办?如果可能的话,是很方便(性能和可读性明智)?
If it is possible how would I do it using Stream? If it is possible, is it convenient (performance and readability wise)?
推荐答案
在这里,你有一个产生的,而不是数组修改previously定义变量的解决方法:
Here you have a solution that produces the array instead of modifying a previously defined variable:
String[][] array =
IntStream.range(0, 3)
.mapToObj(x -> IntStream.range(0, 3)
.mapToObj(y -> String.format("%c%c", letter(x), letter(y)))
.toArray(String[]::new))
.toArray(String[][]::new);
如果你想使用并行流,那么,以避免副作用,如一个变量(数组或对象)的修改,这是非常重要的。这可能会导致竞争条件或其他并发问题。您可以阅读<一个更多有关href=\"https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html\">java.util.stream包文档 - 见的非干扰的无国籍行为的和的副作用的部分。
If you want to use parallel streams then it's very important to avoid side effects like modifications of a variable (array or object). It might lead to race conditions or other concurrency issues. You can read more about that in java.util.stream package documentation - see Non-interference, Stateless behaviors and Side-effects sections.
这篇关于灌装使用流多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!