2

So I have an Integer[][] data that I want to convert into an ArrayList<ArrayList<Integer>>, so I tried using streams and came up with the following line:

ArrayList<ArrayList<Integer>> col = Arrays.stream(data).map(i -> Arrays.stream(i).collect(Collectors.toList())).collect(Collectors.toCollection(ArrayList<ArrayList<Integer>>::new));

But the last part collect(Collectors.toCollection(ArrayList<ArrayList<Integer>>::new)) gives me an error that it cannot convert ArrayList<ArrayList<Integer>> to C.

2
  • 4
    If you don't need a specific List implementation, you can do List<List<Integer>> col = Arrays.stream(data).map(Arrays::asList).collect(Collectors.toList()); Commented May 3, 2016 at 9:19
  • @AlexisC. this should be the answer Commented May 3, 2016 at 13:39

1 Answer 1

4

The inner collect(Collectors.toList() returns a List<Integer>, not ArrayList<Integer>, so you should collect these inner Lists into an ArrayList<List<Integer>> :

ArrayList<List<Integer>> col = 
    Arrays.stream(data)
          .map(i -> Arrays.stream(i)
                          .collect(Collectors.toList()))
          .collect(Collectors.toCollection(ArrayList<List<Integer>>::new));

Alternately, use Collectors.toCollection(ArrayList<Integer>::new) to collect the elements of the inner Stream :

ArrayList<ArrayList<Integer>> col = 
     Arrays.stream(data)
           .map(i -> Arrays.stream(i)
                           .collect(Collectors.toCollection(ArrayList<Integer>::new)))
           .collect(Collectors.toCollection(ArrayList<ArrayList<Integer>>::new));
Sign up to request clarification or add additional context in comments.

2 Comments

Ah, I see. I thought it would cast List to ArrayList on it's own. Thanks!
You don’t need to write such prose at constructor references. Thanks to type inference, writing ArrayList::new is enough. And I wouldn’t use a stream operation for the inner array conversion, .map(sub -> new ArrayList<>(Arrays.asList(sub))) is much simpler…

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.