【问题标题】:Split list into smaller lists of n-size with stream [duplicate]使用流将列表拆分为较小的 n 大小列表 [重复]
【发布时间】:2017-12-04 17:33:47
【问题描述】:

如何在 Java 中使用流将 Java 列表拆分为大小为 n 的较小列表?

在 JavaScript 中,我会使用 reduce() 函数并执行以下操作:

const n = 3;
const sublists = [1,2,3,4,5,6,7,8,9,0]
  .reduce((r, i) => {
    r[r.length - 1].length == n 
      ? r.push([i])
      : r[r.length - 1].push(i);
    return r;
  }, [[]]);
console.log(sublists);

我正在尝试使用 Java 流来做到这一点,但我似乎无法弄清楚如何让它让我使用 ArrayList<ArrayList<Integer>> 作为我的初始值,然后添加列表。我有点困惑组合器和累加器如何让我使用它们,或者即使 reduce() 是 Java 的最佳方法。

【问题讨论】:

标签: java


【解决方案1】:

看起来您有一个 JavaScript 数组,因此等效的 Java 代码可能会使用 IntStream。首先,计算rows的正确数量,然后使用Arrays.copyOfRange收集到List,然后转换为int[][]。最后,使用Arrays.deepToString 打印数组。喜欢,

final int n = 3;
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int rows = 1 + arr.length / n;
int[][] sublists = IntStream.range(0, rows)
        .mapToObj(i -> 
                Arrays.copyOfRange(arr, n * i, Math.min(n + (n * i), arr.length)))
        .collect(Collectors.toList()).toArray(new int[rows][n]);
System.out.println(Arrays.deepToString(sublists));

哪些输出

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

对于List<Integer>,可能会这样做

final int n = 3;
List<Integer> arr = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);
int rows = 1 + arr.size() / n;
List<List<Integer>> sublists = IntStream.range(0, rows)
        .mapToObj(i -> arr.subList(n * i, Math.min(n + (n * i), arr.size())))
        .collect(Collectors.toList());
System.out.println(sublists);

对于相同的(请求的)输出。

【讨论】:

  • 谢谢,这看起来像我要找的东西。我实际上有一个List&lt;Integer&gt;,但我应该能够弄清楚转换。
【解决方案2】:

非常简单:

    List<Integer> list = List.of(1, 2, 3, 4, 5, 7, 8, 9, 10, 11);
    int n = 3;
    List<List<Integer>> result = new LinkedList<>();
    int size = list.size();
    for (int i = 0; i <= size; i += n) {
        result.add(list.subList(i, Math.min(i + n, size)));
    }        
    System.out.println(result);  // [[1, 2, 3], [4, 5, 7], [8, 9, 10], [11]]

Java 8 解决方案:

List<Integer> list = List.of(1, 2, 3, 4, 5, 7, 8, 9, 10, 11);
int n = 3;
List<List<Integer>> result = IntStream.range(0, list.size())
    .filter(i -> i % n == 0)
    .mapToObj(i -> list.subList(i, Math.min(i + n, list.size())))
    .collect(Collectors.toList());
System.out.println(result);  // [[1, 2, 3], [4, 5, 7], [8, 9, 10], [11]]

【讨论】:

  • 谢谢,但我应该明确指出我正在寻找一种带有流()的方法。我知道如何使用 for 循环来做到这一点。
  • @samanime 我更新了答案以提供流解决方案
猜你喜欢
  • 1970-01-01
  • 2012-07-12
  • 1970-01-01
  • 2021-02-02
  • 2020-05-05
  • 1970-01-01
  • 2012-03-29
  • 1970-01-01
  • 2012-11-04
相关资源
最近更新 更多