0

I have stream of Integer or Long. I wan to add the element of the stream one by one and compare it with one fixed value after each addition if it met certain criteria need to break the addition and return the value. If we use reduction it will add all the element of the stream but I want add elements until certain condtion is met the break.

Ex
fixed value = 15
1,2,3,4,5,6 --> (1+2+3+4+5) = 15 at this point stop the addition and return this value of some other value like 1 if not equal 15 then return 0.


springbootlearner
  • 1,220
  • 4
  • 26
  • 48
  • Does this answer your question? [Stream stateful computation: cumulative sums](https://stackoverflow.com/questions/28355684/stream-stateful-computation-cumulative-sums) – Joe Sep 04 '21 at 05:12
  • This looks like it could be a re-post of https://stackoverflow.com/questions/69044938/how-to-create-stream-of-integers-dynamically-based-on-certain-condition-while-it, which has already been answered: https://stackoverflow.com/a/69045179/733345 – Joe Sep 04 '21 at 05:27

1 Answers1

0

You want to perform a test on the list of cumulative sums. Suppose your stream is:

var longs = LongStream.iterate(0, i -> i + 1);

This answer suggests a way to derive that:

var ai = new AtomicLong();
var cumulativeSums = longs.map(ai::addAndGet);

You can then find the first matching value.

cumulativeSums.filter(x -> x >= 15).findFirst();

yields an OptionalLong[15].

Joe
  • 29,416
  • 12
  • 68
  • 88