Reputation: 9809
Is this way is the most efficient way to filter and sum using java streams?
public static void main(String[] args){
int[] array = {23,43,56,97,32};
int sum1 = Arrays.stream(array).boxed().filter(e -> 35 < e).reduce(0,(a,b)->a+b);
}
What would a better alternative(if there) and why?
Upvotes: 0
Views: 1225
Reputation: 120848
because reduce
creates new Objects all the time, besides Integer
and int
are different things - summing would require un-boxing and boxing again.
The simpler and faster way would be to work off a IntStream
specialization:
Arrays.stream(array).filter(e -> 35 < e).sum();
Upvotes: 2
Reputation: 328598
There is no need or reason to box your stream - keep using the IntStream
all the way:
int sum1 = Arrays.stream(array).filter(e -> 35 < e).sum();
Upvotes: 6