Java的8个流和操作上的阵列 [英] Java 8 Stream and operation on arrays
问题描述
我刚刚发现了新的Java 8个流能力。在Python来了,我在想,如果现在有一个整洁的方式做像总结阵列作业,在一行Python化的方式相乘两个数组?
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();
乘两个数组是有点困难,因为我不能想办法来获取值,并在同一时间作为流操作的指数。这意味着你可能要流在阵列的索引。
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]);
修改
霍尔格评论者指出,可以使用地图
方法,而不是的forEach
是这样的:
EDIT
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个流和操作上的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!