简体   繁体   English

将列表列表转换为 int 数组

[英]Convert List of Lists to int array

I have input of list of lists which i want to convert into int array which can help for my logic我输入了列表列表,我想将其转换为 int 数组,这有助于我的逻辑

list of Lists "lst" has input [[1,0,1],[1,1,0],[0,0,1]]列表“lst”的列表有输入[[1,0,1],[1,1,0],[0,0,1]]

output array should be like {{1,0,1},{1,1,0},{0,0,1}} output 数组应该像{{1,0,1},{1,1,0},{0,0,1}}

int[] arr = new int[lst.size()];

for(int i=0;i<lst.size();i++){
    for(int j=0;j<lst.size();j++){
        arr[i] =  lst.get(i).get(j);
    }
}

Here are two ways.这里有两种方法。

The data数据

List<List<Integer>> list = List.of(List.of(1,0,1),
                                   List.of(1,1,0),
                                   List.of(0,0,1));
  • allocate an Array of arrays for the number of rows.为行数分配一个 arrays 的数组。
  • iterate over the rows of the data.遍历数据行。
  • create an array to hold the inner array contents创建一个数组来保存内部数组内容
  • fill it and assign to the array of arrays.填充它并赋值给arrays的数组。
int[][] arr = new int[list.size()][];
for (int i = 0; i < list.size(); i++) {
    List<Integer> lst = list.get(i);
    int [] temp = new int[lst.size()];
    for (int k = 0; k < lst.size(); k++) {
        temp[k] = lst.get(k);
    }
    arr[i] = temp;
}

System.out.println(Arrays.deepToString(arr));

Or或者

  • stream the lists of lists stream 列表列表
  • then stream each of those lists, mapping to an int and creating an array.然后 stream 每个列表,映射到一个 int 并创建一个数组。
  • the put those arrays in an Array of arrays.将这些 arrays 放入 arrays 的数组中。
int[][] arr = list.stream()
               .map(ls->ls.stream().mapToInt(a->a).toArray())
               .toArray(int[][]::new);

System.out.println(Arrays.deepToString(arr));

Both print都打印

[[1, 0, 1], [1, 1, 0], [0, 0, 1]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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