Issue
I have an array as:
int[][] bookings= {{6, 7, 20}, {2, 0, 30}, {7, 20, 15}};
Which I want to be:
ArrayList = {
ArrayList<Integer>{6, 7, 20},
ArrayList<Integer>{2, 0, 30},
ArrayList<Integer>{7, 20, 15},
}
How can I achieve that?
I've tried to use:
Arrays.stream(bookings)
.flatMapToInt(x -> Arrays.stream(x))
.boxed()
.collect(Collectors.toList());
But this return only a single Arraylist
, like:
ArrayList list = {6, 7, 20, 2, 0, 30, 7, 20, 15};
Solution
You don't need to flatten your data with flatMapToInt()
, since you need a nested list as a result.
Instead, you need to transform each array into a list, which can be done via map()
operation, you can create a nested stream and collect array contents into a list.
And then collect stream lists into a list.
List<List<Integer>> result = Arrays.stream(bookings) // Stream<int[]>
.map(booking -> Arrays.stream(booking).boxed() // Stream<List<Integer>>
.collect(Collectors.toList()))
.collect(Collectors.toList())
Answered By - Alexander Ivanchenko
Answer Checked By - Candace Johnson (JavaFixing Volunteer)