How to convert a 2D array to a 2D list using Streams?

I tried this StackOverflow response code, but I get an 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());
+4
source share
2 answers

Arrays.streamwill go through int[]in int[][]. You can convert int[]to IntStream. Then, to convert the stream intto List<Integer>, you first need to put them. After you are boxed to Integers, you can put them on a list. And finally, we collect the stream 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 version

+4
source

Try StreamEx

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

AbacusUtil, :

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

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

. , data null

0

Source: https://habr.com/ru/post/1678514/


All Articles