Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert a Nested Array of int into a List of Lists with Streams in Java 8

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading