我怎么能一个阵列的每个元素添加到使用ParallelStream一个又一个的相应元素? [英] How can I add each element of one array to another one's corresponding element using a ParallelStream?

查看:131
本文介绍了我怎么能一个阵列的每个元素添加到使用ParallelStream一个又一个的相应元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我所试图做的是可能使用一个例子更容易解释。假设我有以下两个数组:

What I am trying to do is probably easier explained using an example. Let's assume I have to following two arrays:

int firstArray[] = {1, 2, 3, 4, 5};
int secArray[] = {1, 2, 3, 4, 5};

我要的是增加每个元素 I 第二个数组的每个元素 I 第一个数组的。当然,创造了第三个数组也还可以。

What I want is to add each element i of the second array to each element i of the first array. Of course, creating a third array is also okay.

结果,给出这个例子中,将是: 2,4,6,8,10

The result, given this example, would be: 2, 4, 6, 8, 10

我能做到这一点莫名其妙地在Java中使用8 ParallelStream?我只能想到用至少一个索引的解决方案,而且他们并不真正因为并行的工作(这也违背了目的)。

Can I do this somehow using a ParallelStream in Java 8? I can only think of solutions using at least one index, and they don't really work because of the parallelism (which also defeats the purpose).

这单线程方法工作:

AtomicInteger i = new AtomicInteger(0);
int resultArray[] = Arrays.stream(firstArray)
                          .map(a -> a + secArray[i.getAndIncrement()]).toArray();

但是,如果我尝试这种使用并行流,结果是(当然他们)随机程序实在是太慢了。有任何想法吗?

But if I try this using a parallel stream, the results are (of course they are) random and the program is really slow. Any ideas?

推荐答案

这是一个典型的用例 IntStream

IntStream.range(0, firstArray.length).parallel()
    .forEach(i -> { secArray[i] += firstArray[i]; });

如果你需要在一个单独的数组的结果,你可以用相同的方法:

If you need the result in a separate array, you can use the same approach:

int[] result = IntStream.range(0, firstArray.length).parallel()
    .map(i -> firstArray[i] + secArray[i])
    .toArray();

这篇关于我怎么能一个阵列的每个元素添加到使用ParallelStream一个又一个的相应元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆