ack
ack

Reputation: 1251

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());

Upvotes: 5

Views: 1355

Answers (2)

user_3380739
user_3380739

Reputation: 1254

Try StreamEx

StreamEx.of(data).map(a -> IntStreamEx.of(a).boxed().toList()).toList();

Or abacus-common, simple and most efficient:

Stream.of(data).map(a -> IntList.of(a).boxed()).toList();

// Or:
Seq.of(data).map(a -> IntList.of(a).boxed());

All of them are null safety. An empty list is returned if data is null

Upvotes: 1

janos
janos

Reputation: 124646

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.

Upvotes: 6

Related Questions