Reputation: 9
I'm trying to apply a filter in the sum function.
Integer lyf = events.stream().mapToInteger(i -> i).filter(sum()>100?100:sum());
but I'm facing an error.
Upvotes: 0
Views: 770
Reputation: 4120
You can also do filtering and adding in steam with reduce
:
Integer lyf = events.stream().reduce(0, (acc, v) -> acc > 100 ? 100 : (acc + v));
Other approach with short circuit
to stop when sum > 100 is reached:
AtomicInteger acc = new AtomicInteger(0);
events.stream()
.allMatch(x ->
acc.updateAndGet((a) -> Math.min(100, (a + x) )) < 100
);
Integer lyf = acc.get();
Upvotes: 0
Reputation: 7165
You need to first calculate the sum,
int sum = events.stream().mapToInt(i -> i).sum();
lyf = sum>100 ? 100 : sum;
Update: If you want to short circuit the Stream pipeline once a partial sum > 100 is reached, you can use a filter as below,
AtomicInteger sum = new AtomicInteger(0);
events.stream()
.mapToInt(sum::addAndGet)
.filter(i -> sum.get() > 100)
.mapToObj(i1 -> {
if (sum.get() < 100)
return sum.get();
else
sum.set(100);
return sum;
})
.findAny();
System.out.println(sum.get());
Upvotes: 1
Reputation: 1554
You will need to use one of the short-circuiting
functions of the Stream. In this case I would use the allMatch()
function.
Here's a small test I wrote to verify
@Test
public void testShortCircuitingSum() {
final AtomicInteger totalSum = new AtomicInteger(0);
IntStream.range(0, 1000).allMatch(value -> totalSumLessThan100(totalSum, value));
System.out.println("Final sum is " + totalSum.get());
}
private static boolean totalSumLessThan100(AtomicInteger totalSum, int value) {
if (totalSum.addAndGet(value) <= 100) {
return true;
}
System.out.println("Total sum is " + totalSum.get() + ". Short-Circuiting at value " + value);
System.out.println("Setting the value to 100");
totalSum.set(100);
return false;
}
Which prints
Total sum is 105. Short-Circuiting at value 14
Setting the value to 100
Final sum is 100
Upvotes: 0