来自java中的二维数组的流

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22601036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:45:52  来源:igfitidea点击:

Stream from two dimensional array in java

javamultidimensional-arrayjava-8java-stream

提问by SurenNihalani

I am trying to get an IntStreamout of an n dimensional intarrays. Is there a nice API way to do it? I know the concatenate method for two streams.

我正在尝试IntStream从 n 维int数组中取出一个。有没有很好的 API 方法来做到这一点?我知道两个流的连接方法。

采纳答案by Rohit Jain

Assuming you want to process array of array sequentially in row-major approach, this should work:

假设您想以行优先方法顺序处理数组数组,这应该有效:

int[][] arr = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
IntStream stream = Arrays.stream(arr).flatMapToInt(x -> Arrays.stream(x));

First it invokes the Arrays.stream(T[])method, where Tis inferred as int[], to get a Stream<int[]>, and then Stream#flatMapToInt()method maps each int[]element to an IntStreamusing Arrays.stream(int[])method.

首先它调用Arrays.stream(T[])方法,其中T推断为int[],以获取 a Stream<int[]>,然后Stream#flatMapToInt()方法将每个int[]元素映射到IntStreamusingArrays.stream(int[])方法。

回答by Jacob G.

To further expand on Rohit's answer, a method reference can be used to slightly shorten the amount of code required:

为了进一步扩展 Rohit 的答案,可以使用方法参考来稍微缩短所需的代码量:

int[][] arr = { {1, 2, 3}, 
                {4, 5, 6},
                {7, 8, 9} };

IntStream stream = Arrays.stream(arr).flatMapToInt(Arrays::stream);

回答by Alex K.

To process the elements only, use flatMapas in Rohit's answer.

要仅处理元素,请使用flatMapRohit 的回答。

To process the elements with their indices, you may use IntStream.rangeas follows.

要处理带有索引的元素,您可以使用IntStream.range如下。

import java.util.stream.IntStream;
import static java.util.stream.IntStream.range;

public class StackOverflowTest {
    public static void main(String... args) {
        int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
        // Map the two dimensional array with indices.
        final IntStream intStream = range(0, arr.length).flatMap(row -> range(0, arr[row].length).map(col -> {
            final int element = arr[row][col];
            // E.g. multiply elements in odd numbered rows and columns by two.
            return row % 2 == 1 || col % 2 == 1 ? element * 2 : element;
        }));
        // Prints "1 4 3 8 10 12 7 16 9 ".
        intStream.forEachOrdered(n -> System.out.print(n + " "));
    }
}

回答by fiftyone_51

Adding to the previous answers, the method Arrays::streamreturns a sequential stream (see: Oracle Javadoc). In some situations, a parallel stream might improve performance. To explicitly request a parallel stream, you first need to convert to a List via Arrays::asList, then call parallelStream()on the resulting List.

添加到前面的答案中,该方法Arrays::stream返回一个顺序流(请参阅:Oracle Javadoc)。在某些情况下,并行流可能会提高性能。要显式请求并行流,首先需要通过 转换为 List Arrays::asList,然后调用parallelStream()生成的 List。

To calculate the sum of a two dimensional intarray using a IntStream, you can use following code:

int使用 a计算二维数组的总和IntStream,可以使用以下代码:

int[][] twoDimArray = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
IntStream intStream = Arrays.asList(twoDimArray)
    .parallelStream()               // "rows" in parallel
    .flatMapToInt(Arrays::stream);  // "columns" sequentially
int sum = intStream.sum();          // = 45

The Stream created for processing the outer layer (rows, first dimension) is now executing in parallel, while the Streams for the inner layer (columns, second dimension) are still sequential (using Arrays::streammentioned above).

为处理外层(行,第一维)而创建的流现在并行执行,而内层(列,第二维)的流仍然是顺序的(使用Arrays::stream上面提到的)。

Depending on the size and structure of your array, you might see a performance increase by factor 4 (that's what I measured in my own tests) or none at all. If your calculations are time critical, it might be worth a try to use a parallel Stream.

根据数组的大小和结构,您可能会看到性能提高了 4 倍(这是我在自己的测试中测得的),或者根本没有。如果您的计算对时间要求严格,那么使用并行流可能值得一试。