4

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.

1
  • I just need to run myMethod.getInt() 25000 times. myMethod.getInt() return a random int. Commented Oct 30, 2018 at 11:50

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3
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 :)

9 Comments

With this code I was not able to get the final value of the sum. Like int value = IntStream.range(0, 25000) .map(i -> myMethod.getInt()) .mapToObj(BigInteger::valueOf) .map(value::add) and I got two errors: Error:(16, 96) java: incompatible types: long cannot be converted to java.math.BigDecimal Error:(16, 79) java: incompatible types: no instance(s) of type variable(s) U exist so that java.util.stream.Stream<U> conforms to java.math.BigDecimal
@Roland if value collects the sum you can go with .reduce(BigInteger.valueOf(0), BigInteger::add)
Instead of BigInteger.valueOf(0), you can use BigInteger.ZERO. Alternative solution are IntStream.generate(myMethod::getInt).limit(25000).mapToObj(BigInteger::valueOf) … or Stream.generate(() -> BigInteger.valueOf(myMethod.getInt())).limit(25000) ….
@Michael nope, I posted it as suggestion anyway, not as an answer. Besides that, finding such canonical solutions simultaneously, is not unusual.
@Roland a) wrong benchmark methodology b) whatever happens inside myMethod.getInt() (e.g. using a synchronized random generator). If all this method does, is returning a random int, how about BigInteger result = ThreadLocalRandom.current().ints(25000, [min, max]) [.parallel()] .mapToObj(BigInteger::valueOf).reduce(BigInteger.ZERO, BigInteger::add);? Though, to sum up 25000 int values, you don’t need BigInteger anyway, as even the long value range is sufficient.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.