Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filling a Multidimensional Array using a Stream

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)?

like image 774
Angelo Alvisi Avatar asked Sep 26 '14 01:09

Angelo Alvisi


People also ask

Can you use a stream on an array?

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.

How do you fill a 2D array?

1)Fill 2D Array // given value. int [][]ar = new int [ 3 ][ 4 ]; // Fill each row with 10.

How do I fill a 2D array in C++?

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.


1 Answers

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.

like image 197
Lukasz Wiktor Avatar answered Sep 29 '22 13:09

Lukasz Wiktor