简体   繁体   English

IntStream用于求和2D数组

[英]IntStream to sum a 2D array

What is the syntax for using IntStream to sum a range of elements in a 2D array? 使用IntStream对2D数组中的一系列元素求和的语法是什么?

For a 1D array, I use the following syntax: 对于1D数组,我使用以下语法:

int totalElementsInArray = 0;

totalElementsInarray = IntStream.of(myArray).sum();

So for instance, say I have a 2D array: 例如,假设我有一个2D数组:

int[][] my2DArray = new int[17][4];

What is the syntax when using IntStream for summing columns 0-16 on row 0? 使用IntStream对第0行的第0-16列求和时的语法是什么?

int totalElementsInArray = 0;

totalElementsInarray = IntStream.of(my2DArray[0 through 16][0]).sum();

You just need to map each sub-array to an int by taking the first element: 您只需要通过获取第一个元素将每个子数组映射到int

import java.util.*;
import java.util.stream.*; 

class Test {
    public static void main(String args[]) {
        int[][] data = {
            { 1, 2, 3 },
            { 4, 5, 6 }
        };

        int sum = Arrays.stream(data)
                        .mapToInt(arr -> arr[0])
                        .sum();
        System.out.println(sum); // 5, i.e. data[0][0] + data[1][0]
    } 
}

In other words: 换一种说法:

  • Transform data to a Stream<int[]> (ie a stream of simple int arrays) data转换为Stream<int[]> (即简单的int数组流)
  • Map each array to its first element, so we end up with an IntStream 将每个数组映射到其第一个元素,因此我们最终得到一个IntStream
  • Sum that stream 汇总流

I prefer this approach over the approaches using range , as there seems no need to consider the indexes of the sub-arrays. 我更喜欢这种方法而不是使用range的方法,因为似乎不需要考虑子数组的索引。 For example, if you only had an Iterable<int[]> arrays you could still use StreamSupport.stream(arrays.spliterator(), false).mapToInt(arr -> arr[0]).sum() , whereas the range approach would require iterating multiple times. 例如,如果你只有一个Iterable<int[]> arrays你仍然可以使用StreamSupport.stream(arrays.spliterator(), false).mapToInt(arr -> arr[0]).sum() ,而范围方法需要多次迭代。

One way to do it would be to create a IntStream over the indexes 一种方法是在索引上创建一个IntStream

IntStream.range(0, my2DArray.length).map(i -> my2DArray[i][0]).sum();

or only keep the first row of the result of Arrays.stream : 或者只保留Arrays.stream结果的第一行:

Arrays.stream(my2DArray).mapToInt(a -> a[0]).sum();

You can do it like this 你可以这样做

IntStream.range(0, 17)
         .map(i -> my2DArray[i][0])
         .sum();

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

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