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

How to convert a matrix to a List of List in Java?

I have a 2d matrix like this String[][] arr; and I want to convert it into List<List<String>>arr;. How can I do achieve that?

I saw some similar answers related to my question on this community but they were about how to convert a matrix in List<T>.

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

>Solution :

For that purpose, you can make use of the asList() static method of the Arrays utility class. Simply iterate over the source array and apply asList() to every nested array.

        List<List<String>> result = new ArrayList<>();
        for (String[] next: arr) {
            result.add(Arrays.asList(next));
        }

Note, that asList() method returns a list backed by the specified array, and therefore it can’t be changed in size (you can sort it, reassign values, but its add() and remove() methods will throw an UnsupportedOperationException). Changes that have been done to the list will be reflected in the source array and vice-versa.

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