从数组创建列表列表

xmjla07d  于 2021-09-13  发布在  Java
关注(0)|答案(4)|浏览(510)

如何从数组中创建列表,例如: int[] arr = {3, 1, 5, 8, 2, 4} . 使列表中的列表只有两个元素,例如: [[3,1], [5,8], [2,4]] .
到目前为止,我已经尝试了下面的代码,但它只返回带有一个元素的列表,我不知道哪里出错了。

  1. class ListList {
  2. public static List<List<Integer>> listOfList(int[] num){
  3. List<List<Integer>> arrList = new ArrayList<>();
  4. for(int i = 0 ; i<num.length;i++){
  5. List<Integer> list = new ArrayList<>();
  6. if(list.size() !=2){
  7. list.add(num[i]);
  8. }
  9. arrList.add(list);
  10. }
  11. return arrList;
  12. }
  13. }

结果: [[3], [1], [5], [8], [2], [4]] .

lh80um4z

lh80um4z1#

如果确定列表中有偶数个值,可以这样做。
创建列表列表。
一次两个,把每个放在一个单独的列表中
将该列表添加到列表列表中

  1. int [] arr ={3, 1, 5, 8, 2, 4};
  2. List<List<Integer>> list = new ArrayList<>();
  3. for (int i = 0; i < arr.length; i+=2) {
  4. List<Integer> temp = Arrays.asList(arr[i], arr[i+1]);
  5. list.add(temp);
  6. }
  7. System.out.println(list);

印刷品

  1. [[3, 1], [5, 8], [2, 4]]

如果列表长度为奇数,请将赋值更改为

  1. List<Integer> temp = arr.length - i >= 2 ? Arrays.asList(arr[i], arr[i+1]) :
  2. Arrays.asList(arr[i]);

这里是一个使用流的类似解决方案。
在for循环中进行迭代
Map取决于数组长度的奇偶性
并返回一个列表列表。

  1. List<List<Integer>> lists = IntStream
  2. .iterate(0, i->i < arr.length, i->i+= 2)
  3. .mapToObj(i -> arr.length - i >= 2 ?
  4. Arrays.asList(arr[i], arr[i + 1]) :
  5. Arrays.asList(arr[i]))
  6. .toList(); // java 16 or .collect(Collectors.toList());
展开查看全部
mqxuamgl

mqxuamgl2#

在每次迭代中创建一个空列表,然后检查 size != 2 (当然是)并添加1个元素,最后将包含1个元素的列表添加到结果列表中,这不是您所需要的。
将列表创建移出循环并向其中添加元素。当它 size == 2 ,将当前列表添加到结果列表并创建一个新列表。

  1. class ListList {
  2. public static List<List<Integer>> listOfList(int[] num) {
  3. List<List<Integer>> arrList = new ArrayList<>();
  4. List<Integer> list = new ArrayList<>();
  5. for(int i = 0; i < num.length; i++) {
  6. if(list.size() == 2) {
  7. arrList.add(list);
  8. list = new ArrayList<>();
  9. }
  10. list.add(num[i]);
  11. }
  12. if(list.size() != 0) {
  13. arrList.add(list);
  14. }
  15. return arrList;
  16. }
  17. }

若您的输入大小可以是奇数,那个么您还应该将长度为1的列表添加到结果列表中。如果不想,请添加传统支票。

展开查看全部
dojqjjoe

dojqjjoe3#

这里有一个通用的:

  1. var arr = new int[] {3, 1, 5, 8, 2, 4};
  2. var batchSize = 2;
  3. List<List<Integer>> lists = IntStream.range(0, arr.length)
  4. .mapToObj(index -> Map.entry(index, arr[index]))
  5. .collect(Collectors.groupingBy(e -> e.getKey() / batchSize))
  6. .values().stream()
  7. .map(entries -> entries.stream().map(Map.Entry::getValue).toList())
  8. .toList();
  9. System.out.println(lists);

输出:

  1. [[3, 1], [5, 8], [2, 4]]

您基本上是在创建索引->值的Map,然后根据batchsize进行分组以进行拆分

展开查看全部
llew8vvj

llew8vvj4#

试试这个:

  1. public static List<List<Integer>> listOfList(int[] num){
  2. List<List<Integer>> arrList = new ArrayList<>();
  3. for (int i = 0; i < num.length; i += 2) {
  4. if (num.length > i + 1) {
  5. arrList.add(List.of(num[i], num[i+1]));
  6. } else {
  7. arrList.add(List.of(num[i]));
  8. }
  9. }
  10. return arrList;
  11. }

在您的示例中,您总是在循环中创建一个新列表,因此大小始终为0,而不是2。

相关问题