Home > Net >  replace the usual for loop with a stream
replace the usual for loop with a stream

Time:04-03

I have simple class CountBarrier with method count() and I want to replace something like that:

for (int i = 0; i < 5; i  ) {
    countBarrier.count()
}

to:

 IntStream.range(0, 5).forEach(countBarrier::count);

but to work properly I can write only this :

IntStream.range(0, 5).forEach((i) -> countBarrier.count());

how to manage this issue(dont want to see var i)?

CodePudding user response:

The method reference that you are passing into the forEach() is classified as a reference to an instance method of a particular object.

containingObject::instanceMethodName    

Compiler by default will assume an integer element of the stream needs to be used as a method parameter.

Because your method count() takes no parameters, you are getting a compilation error. If you had an overload version like count(int) then forEach(countBarrier::count) will compile.

The important thing to note is that you are misusing the Stream API here by changing the state of the object outside the stream. You don't need a stream for this operation.

CodePudding user response:

There is no better alternative. You could write your own method converting countBarrier::count into a Consumer<Integer>, but there is not, generally, a way to do what you're trying to do better than what you have.

  • Related