简体   繁体   中英

Convert List to 2D Array (Java)

I'm a beginner in programming and I have a method :

 public int[][] toArray(List<Integer> list, int rows) {
        int[][] result = new int[list.size()][rows];
        int i = 0;
        int j = 0;
            for (Integer value : list) {
                result[i][j] = value;
                j++;
                if(j > rows - 1){
                    i++;
                    j = 0;
                }
            }
        return result;
    }

The result of it, if rows = 2 (and if we have a list contains numbers from 1 to 7) is:

[[1, 2], [3, 4], [5, 6], [7, 0], [0, 0], [0, 0], [0, 0]]

If rows = 3 result is:

[[1, 2, 3], [4, 5, 6], [7, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

What I need :

[[1, 2], [3, 4], [5, 6], [7, 0]] 

[[1, 2, 3], [4, 5, 6], [7, 0, 0]]

How to do that?

Just for fun, here's another approach using Streams and Guava:

public static int[][] toArray(List<Integer> list, int rows) {
    return Lists.partition(list, rows)
            .stream()
            .map(Ints::toArray)
            .map(a -> Arrays.copyOf(a, rows))
            .toArray(int[][]::new);
}

You can use a counter to track the count and determine the position by counter/rows and counter%rows , eg:

public int[][] toArray(List<Integer> list, int rows) {
    int[][] result = new int[list.size()][rows];
    int counter = 0;
    for (Integer value : list) {
        result[counter/rows][counter%rows] = value;
        counter++;
    }
    return result;
}

You don't need to worry about remaining places as all the MxN elements get initialised with 0 when you declare an array with size.

The problem lies in this line of code:

int[][] result = new int[list.size()][rows];

As you are initializing the result to a 2D array having rows equals to list.size() you are getting always seven rows. The solution is to first compute the number of rows for result array properly and then initialize it.

int resultRows = list.size()/rows;
if(list.size()%rows!=0){
    resultRows++;
}
int[][] result = new int[resultRows][rows];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM