IUnknown
IUnknown

Reputation: 9809

How to use stream filter and sum

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

Answers (2)

Eugene
Eugene

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

assylias
assylias

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

Related Questions