To fill a two-dimensional array with data using a Stream
in Java, you can use the map()
method to transform each element of the stream into an array, and then use the toArray()
method to collect the elements into a two-dimensional array.
Here's an example of how to do it:
import java.util.Arrays; import java.util.List; import java.util.stream.IntStream; import java.util.stream.Stream; public class Main { public static void main(String[] args) { // Create a list of lists List<List<Integer>> list = Arrays.asList( Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6), Arrays.asList(7, 8, 9) ); // Convert the list to a stream and map each element to an array Stream<int[]> stream = list.stream().map(l -> l.stream().mapToInt(i -> i).toArray()); // Collect the stream into a two-dimensional array int[][] array = stream.toArray(int[][]::new); // Print the array for (int[] row : array) { System.out.println(Arrays.toString(row)); } } }
This code creates a list of lists, and then converts it to a stream of arrays using the map()
method. The toArray()
method is used to collect the elements of the stream into a two-dimensional array.
Note that the toArray()
method takes a IntFunction
as an argument, which is used to create the array. In this case, we use int[][]::new
to create a two-dimensional array of int
s.
You can use a similar approach to fill a two-dimensional array with any type of data, as long as you use the appropriate method to convert the data to an array.