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)?
The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source.
1)Fill 2D Array // given value. int [][]ar = new int [ 3 ][ 4 ]; // Fill each row with 10.
2-D Array filling using std::fill or std::fill_n flags[0][0], &a. flags[0][0] + sizeof(a. flags) / sizeof(a. flags[0][0]), '0'); // or using `std::fill_n` // std::fill_n(&a.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With