Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a 2D array to a 2D list with Streams?

I've tried this StackOverflow answer's code, but I get the error Cannot infer type argument(s) for <R> map(Function<? super T,? extends R>):

//data is int[][]
Arrays.stream(data)
    .map(i -> Arrays.stream(i)
        .collect(Collectors.toList()))
            .collect(Collectors.toList());
like image 913
ack Avatar asked Jun 04 '17 19:06

ack


People also ask

How do I turn an array into a stream?

Program 1: Arrays. stream() to convert string array to stream. Program 2: Arrays. stream() to convert int array to stream.

How do I turn an array into a 2D array?

Use reshape() Function to Transform 1d Array to 2d Array The number of components within every dimension defines the form of the array. We may add or delete parameters or adjust the number of items within every dimension by using reshaping. To modify the layout of a NumPy ndarray, we will be using the reshape() method.


1 Answers

Arrays.stream will go through each int[] in the int[][]. You can convert an int[] to an IntStream. Then, in order to convert a stream of ints to a List<Integer>, you first need to box them. Once boxed to Integers, you can collect them to a list. And finally collect the stream of List<Integer> into a list.

List<List<Integer>> list = Arrays.stream(data)
    .map(row -> IntStream.of(row).boxed().collect(Collectors.toList()))
    .collect(Collectors.toList());

Demo.

like image 180
janos Avatar answered Oct 13 '22 22:10

janos