将列表转换为2D数组(Java)

时间:2017-03-16 19:46:37

标签: java multidimensional-array

我是编程的初学者,我有一个方法:

 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;
    }

如果rows = 2(如果我们的列表包含从1到7的数字)的结果是:

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

如果rows = 3结果为:

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

我需要什么

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

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

怎么做?

3 个答案:

答案 0 :(得分:1)

只是为了好玩,这是使用Streams和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);
}

答案 1 :(得分:0)

您可以使用<div id="nav"> <ul> <li>Home</li> <li>Store</li> <li>About me</li> <li>Contact</li> </ul> </div> <img id="move" src="https://scontent.xx.fbcdn.net/v/t1.0-9/16425751_1848826525393050_4826825314980823096_n.jpg?oh=1228198713ee79012631342e3bb4b650&oe=596D7646" width="300" height="300" align="left"> <div class="profile"> <h2>Samuel Wu</h2> <p>Age: 24</p> <p>Sex: Male</p> <p>Height: 5'7</p> </div> <iframe width="320" height="200" src="https://www.youtube.com/embed/zCUlm9F-P9E?ecver=1" frameborder="0" allowfullscreen></iframe> <form> <h3> What do you think about Samuel Wu?</h3> <input type="text" value="just fk me up fam"> <p>Did you answer honestly?<input type="checkbox"></p> <h3>How well do you think you know Samuel Wu?</h3> <p>What is his favorite color?</p> <select> <option>red</option> <option>blue</option> <option>green</option> </select> <p><input type="submit" value="$5 to submit"></p> </form> <div id="times"> <table> <thead> <tr> <th>x</th> <th>1</th> <th>2</th> <th>3</th> </tr> </thead> <tbody> <tr> <th>1</th> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <th>2</th> <td>2</td> <td>4</td> <td>6</td> </tr> <tr> <th>3</th> <td>3</td> <td>6</td> <td>9</td> </tr> </tbody> </table> </div>跟踪计数并按countercounter/rows确定排名,例如:

counter%rows

当您声明具有大小的数组时,您不必担心剩余的位置,因为所有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; } 元素都会被初始化为0.

答案 2 :(得分:0)

问题出在这行代码中:

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

当您将结果初始化为行数等于list.size()的2D数组时,您总是会获得七行。解决方案是首先正确计算结果数组的行数,然后初始化它。

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