Java 8 Stream 和对数组的操作 [英] Java 8 Stream and operation on arrays
问题描述
我刚刚发现了新的 Java 8 流功能.来自 Python,我想知道现在是否有一种巧妙的方法来对数组进行运算,例如求和,以一行 pythonic"方式将两个数组相乘?
I have just discovered the new Java 8 stream capabilities. Coming from Python, I was wondering if there was now a neat way to do operations on arrays like summing, multiplying two arrays in a "one line pythonic" way ?
谢谢
推荐答案
java.util.Arrays
中添加了一些新方法,可以将数组转换为 Java 8 流,然后可以将其用于求和等
There are new methods added to java.util.Arrays
to convert an array into a Java 8 stream which can then be used for summing etc.
int sum = Arrays.stream(myIntArray).sum();
将两个数组相乘有点困难,因为我想不出一种方法可以在 Stream 操作的同时获取值和索引.这意味着您可能必须对数组的索引进行流式处理.
Multiplying two arrays is a little more difficult because I can't think of a way to get the value AND the index at the same time as a Stream operation. This means you probably have to stream over the indexes of the array.
//in this example a[] and b[] are same length
int[] a = ...
int[] b = ...
int[] result = new int[a.length];
IntStream.range(0, a.length).forEach(i -> result[i] = a[i] * b[i]);
评论员 @Holger 指出您可以使用 map
方法代替 forEach
像这样:
Commenter @Holger points out you can use the map
method instead of forEach
like this:
int[] result = IntStream.range(0, a.length).map(i -> a[i] * b[i]).toArray();
这篇关于Java 8 Stream 和对数组的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!