36

I have am X n two dimensional array of an Object say Foo. So I have Foo[][] foosArray. What is the best way to convert this into a List<Foo> in Java?

Inquisitive
  • 7,476
  • 14
  • 50
  • 61

15 Answers15

40

This is a nice way of doing it for any two-dimensional array, assuming you want them in the following order:

[[array[0]-elems], [array[1]elems]...]

public <T> List<T> twoDArrayToList(T[][] twoDArray) {
    List<T> list = new ArrayList<T>();
    for (T[] array : twoDArray) {
        list.addAll(Arrays.asList(array));
    }
    return list;
}
Keppil
  • 45,603
  • 8
  • 97
  • 119
22

Since

List<Foo> collection = Arrays.stream(array)  //'array' is two-dimensional
    .flatMap(Arrays::stream)
    .collect(Collectors.toList());
Jeffmagma
  • 452
  • 2
  • 8
  • 20
Tomasz Mularczyk
  • 34,501
  • 19
  • 112
  • 166
  • 2
    I want to convert int [ ] [ ] array to List< List >. I get an error - Bad return type in method reference: cannot convert java.util.stream.IntStream to java.util.stream.Stream>. How do I fix this ? – MasterJoe Jul 18 '20 at 06:21
19

This can be done using Java 8 stream API this way:

String[][] dataSet = new String[][] {{...}, {...}, ...};
List<List<String>> list = Arrays.stream(dataSet)
                               .map(Arrays::asList)
                               .collect(Collectors.toList());

Basically, you do three things:

  • Convert the 2-d array into stream
  • Map each element in stream (which should be an array) into a List using Arrays::asList API
  • Reduce the stream into a new List
1000Nettles
  • 2,314
  • 3
  • 22
  • 31
nybon
  • 8,894
  • 9
  • 59
  • 67
14
for(int i=0;i<m;i++)
    for(int j=0;j<n;j++)
        yourList.add(foosArray[i][j]);

I think other tricks are unnecessary, because, anyway, they'll use this solution.

Dmitry Zaytsev
  • 23,650
  • 14
  • 92
  • 146
4

Here is a step by step solution to convert a 2D array of int (i.e. primitive data types) to a list. The explanations are in the code comments.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Temp {
    public static void main(String... args) {
        System.out.println("Demo...");
        int [] [] twoDimArray = new int[][]{
                {1,2}, {3,5}, {8,15}
        };

        List< List<Integer> > nestedLists =
                Arrays.
                //Convert the 2d array into a stream.
                stream(twoDimArray).
                //Map each 1d array (internalArray) in 2d array to a List.
                map(
                        //Stream all the elements of each 1d array and put them into a list of Integer.
                        internalArray -> Arrays.stream(internalArray).boxed().collect(Collectors.toList()
                    )
        //Put all the lists from the previous step into one big list.
        ).collect(Collectors.toList());

        nestedLists.forEach(System.out::println);
        
    }
}

Output :

Demo...
[1, 2]
[3, 5]
[8, 15]
MasterJoe
  • 2,103
  • 5
  • 32
  • 58
3

The only way to transform it to a list is to iterate through the array and build the list as you go, like this:

ArrayList<Foo[]> list = new ArrayList<Foo[]>(foosArray.length);
for(Foo[] foo: foosArray){
    list.add(foo);
}
Razvan
  • 9,925
  • 6
  • 38
  • 51
3

Use java8 "flatMap" to play around. One way could be following

List<Foo> collection = Arrays.stream(array).flatMap(Arrays::stream).collect(Collectors.toList());
Amit
  • 656
  • 1
  • 6
  • 19
1

Please note that: while working on arrays conversion as a list there is difference between primitive array and Object array. i.e) int[] and Integer[]

e.g)

int [][] twoDArray = {     
        {1,  2,  3,  4,  40},
        {5,  6,  7,  8,  50},
        {9,  10, 11, 12, 60},
        {13, 14, 15, 16, 70},
        {17, 18, 19, 20, 80},
        {21, 22, 23, 24, 90},
        {25, 26, 27, 28, 100},
        {29, 30, 31, 32, 110},
        {33, 34, 35, 36, 120}};

List list = new ArrayList();
for (int[] array : twoDArray) {
    //This will add int[] object into the list, and not the int values.
    list.add(Arrays.asList(array));
}

and

Integer[][] twoDArray = {     
        {1,  2,  3,  4,  40},
        {5,  6,  7,  8,  50},
        {9,  10, 11, 12, 60},
        {13, 14, 15, 16, 70},
        {17, 18, 19, 20, 80},
        {21, 22, 23, 24, 90},
        {25, 26, 27, 28, 100},
        {29, 30, 31, 32, 110},
        {33, 34, 35, 36, 120}};

List list = new ArrayList();
for (Integer[] array : twoDArray) {
    //This will add int values into the new list 
    // and that list will added to the main list
    list.add(Arrays.asList(array));      
}

To work on Keppil answer; you have to convert your primitive array to object array using How to convert int[] to Integer[] in Java?

Else add the int values one by one in the normal for loop.

int iLength = twoDArray.length;
List<List<Integer>> listOfLists = new ArrayList<>(iLength);
for (int i = 0; i < iLength; ++i) {
    int jLength = twoDArray[0].length;
    listOfLists.add(new ArrayList(jLength));
    for (int j = 0; j < jLength; ++j) {
      listOfLists.get(i).add(twoDArray[i][j]);
    }
}

Also note that Arrays.asList(array) will give fixed-size list; so size cannot be modified.

Community
  • 1
  • 1
Kanagavelu Sugumar
  • 18,766
  • 20
  • 94
  • 101
1

E.g.

Integer[][] a = { { 1, 2, 3 }, { 4, 5, 6 }, { 9, 8, 9 }, };
        
List<List<Integer>> arr = Arrays.stream(a)
                .map(Arrays::asList)
                .collect(Collectors.toList());
Hanamant Jadhav
  • 627
  • 7
  • 12
0

another one technique.

//converting 2D array to string
String temp = Arrays.deepToString(fooArr).replaceAll("\\[", "").replaceAll("\\]", "");
List<String> fooList = new ArrayList<>(Arrays.asList(","));
Yogi
  • 1,527
  • 15
  • 21
0
ArrayList<Elelement[]> allElelementList = new ArrayList<>(allElelements.length);
    allElelementList.addAll(Arrays.asList(allElelements));

allElelements is two-dimensional

mrclrchtr
  • 948
  • 10
  • 14
0

Let's add some primitive type arrays processing. But you may pass to parameter any object. Method correctly process as int[][] as Object[][]:

 public <T, E> List<E> twoDArrayToList(T twoDArray) {

   if (twoDArray instanceof int[][])
     return Arrays.stream((int[][])twoDArray)
                  .flatMapToInt(a->Arrays.stream(a))
                  .mapToObj(i->(E)Integer.valueOf(i))
                  .collect(Collectors.toList());

   //… processing arrays of other primitive types 

   if (twoDArray instanceof Object[][])
        return Arrays.stream((E[][])twoDArray)
               .flatMap(Arrays::stream)
               .collect(Collectors.toList());

   return null; // better to throw appropriate exception 
                // if parameter is not two dimensional array
}
Sergey Afinogenov
  • 2,137
  • 4
  • 13
0

In Java 8 , to convert from int[][] to List<Integer>, you can use the below code :

List<Integer> data = Arrays.stream(intervals)
              .flatMapToInt(Arrays::stream)
              .boxed()
              .collect(Collectors.toList());
Jayanth
  • 746
  • 6
  • 17
0
List<Foo> list =  Arrays.stream(fooArray)
      .flatMap(e -> Stream :: of).collect(Collectors.toList());
Manoj H U
  • 37
  • 9
0

Some of the comments in the above answers are asking:

How can we convert an int[][] to ArrayList> ?

This can be a good way to do that:

List<List<Integer>> convertTo2DList(int[][] intervals){
List<List<Integer>> list = new ArrayList<>();
for (int[] arr : intervals) 
{
    List<Integer> temp=new ArrayList<>();
    for(int i:arr) temp.add(i);
    list.add(temp);
}
return list;
}