Java 折叠数组列表

Java fold arraylists

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

+[0, 0, 0,-1, 1, 0, 0, 0, 0, 0, 0,-1, 0, 0, 1, 0, 0, 0, 0, 0]

+[0, 0, 0, 1, 0, 0, 0,-1, 0, 0,-1, 0, 0, 0, 0, 0, 1, 0, 0, 0]

+[0, 1, 0, 0, 0, 0, 0, 1, 0, 0,-1,-1, 0, 0, 0, 0, 0, 0, 0, 0]

=[0, 2, 0, 0, 1, 0, 0, 1, 0, 0,-3,-3, 0, 0, 1, 0, 1, 0, 0, 0]

是否有 Java 函数来执行上述操作,或者我是否必须遍历所有列表?我的最小列表大约有 3k 个元素,平均大约有 20k 个。

您将需要至少 1 个 for 循环,使用它对所有数组的索引,如 result[i]=arr[i]+arr2[i]+....+arrn[i];

如果每个数组的长度不同,首先您需要在尝试访问元素之前检查您是否在其范围内。

一种方法是使用 Java 8 Streams。我认为 reduce() 函数等同于 F# fold()。例如:

public static void main(String[] args) {
    List<List<Integer>> lists = new ArrayList<>();
    lists.add(Arrays.asList(0, 1, 0, 0, 0, 0, 0, 1, 0, 0,-1,-1, 0, 0, 0, 0, 0, 0, 0, 0));
    lists.add(Arrays.asList(0, 0, 0,-1, 1, 0, 0, 0, 0, 0, 0,-1, 0, 0, 1, 0, 0, 0, 0, 0));
    lists.add(Arrays.asList(0, 0, 0, 1, 0, 0, 0,-1, 0, 0,-1, 0, 0, 0, 0, 0, 1, 0, 0, 0));
    lists.add(Arrays.asList(0, 1, 0, 0, 0, 0, 0, 1, 0, 0,-1,-1, 0, 0, 0, 0, 0, 0, 0, 0));

    int n = lists.get(0).size();
    // Reduce each column to the sum of the elements in the column
    // For example:
    //     i = 0 -> 0 + 0 + 0 + 0 = 0
    //     i = 1 -> 1 + 0 + 0 + 1 = 2
    IntUnaryOperator sumElementsInPosition = i -> lists.stream()
                                                       .map(l -> l.get(i))
                                                       .reduce(0, (a, b) -> a + b);

    // For each position i, map the position to the sum of elements in that position
    List<Integer> sum = IntStream.range(0, n)
                                 .map(sumElementsInPosition)
                                 .boxed()
                                 .collect(Collectors.toList());

    System.out.println(sum);
}

输出:

[0, 2, 0, 0, 1, 0, 0, 1, 0, 0, -3, -3, 0, 0, 1, 0, 1, 0, 0, 0]