1

Update: use Integer[][] as as src array type could make the following code work.


I want to convert int[][] to List<List<Integer>> and tried with:

int[][] arr = new int[][]{{2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}};
List<List<Integer>> ll = Arrays.stream(arr)
        .map(Arrays::asList) //  I expect this produces Stream<List<Integer>> but it was actually a Stream<List<int[]>>.
        .collect(Collectors.toList());

the compiler emits an error:

|  Error:
|  incompatible types: inference variable T has incompatible bounds
|      equality constraints: java.util.List<java.lang.Integer>
|      lower bounds: java.util.List<int[]>
|          List<List<Integer>> ll = Arrays.stream(arr).map(Arrays::asList).collect(Collectors.toList());
|                                   ^-----------------------------------------------------------------^
2
  • @Naman I don't see how this question is a duplicate of any of the linked questions. Commented Jul 15, 2020 at 3:56
  • @hev1 Did you go through this answer? Commented Jul 15, 2020 at 4:50

1 Answer 1

5

Arrays.asList doesn't work with primitives (at least, not in the way you intend: Arrays.asList(new int[n]) is a List<int[]> with one element, not a List<Integer> with n elements).

Instead, map to an IntStream (to give you an IntStream), box the elements (to give you a Stream<Integer>), and collect to a list (to give you a List<Integer>:

List<List<Integer>> ll = Arrays.stream(arr)
    .map(a -> IntStream.of(a).boxed().collect(toList()))
    .collect(toList());

Note that if you're using Guava, you could use Ints.asList:

List<List<Integer>> ll = Arrays.stream(arr)
    .map(Ints::asList)
    .collect(toList());

Other libraries may well also have int[] -> List<Integer> methods; this is merely one I know exists.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.