Roland
Roland

Reputation: 681

How to transform a for loop into stream loop

How to transform this code into a stream loop:

for(long l = 1L; l <= 250000; l++) {
     v = value.add(BigInteger.valueOf(myMethod.getInt()));
}

I need to get the 'v' as a unique BigInteger value.

Upvotes: 4

Views: 110

Answers (2)

Ilya Zinkovich
Ilya Zinkovich

Reputation: 4410

BigInteger result = IntStream.range(0, 25000)
  .map(i -> myMethod.getInt())
  .mapToObj(BigInteger::valueOf)
  .reduce(BigInteger.valueOf(0), BigInteger::add)

Another answer with IntStream.generate(myMethod::getInt) and limit is more elegant :)

Upvotes: 3

Michael
Michael

Reputation: 44150

Fundamentally, it looks like your myMethod.getInt method is a generator. Therefore, the best way to do this, in my opinion, is to create an infinite stream from your generator.

IntStream.generate(myMethod::getInt)
    .mapToObj(BigInteger::valueOf)
    .limit(25000)
    .reduce(BigInteger.ZERO, BigInteger::add)

This is clearer because you don't have to specify a range - the range is not what you care about, the number of elements is (i.e. the size of the range). You also don't have to ignore the parameter when you're mapping.

Upvotes: 4

Related Questions