I am using .peek() in my stream but it is frowned upon, sadly I can't find a solution.
Simplified version:
static boolean fooAddTester(int size) {
Foo foo = new foo(); //data structure
return IntStream.range(0, size).
.peek(i -> synchronized(r){foo.add(i)})
.allMatch(e -> foo.isLegal());
}
what I need to do is to iterate over the IntStream and to check after every insert if the foo data structure is legal. This is logically equivalent to:
static boolean fooAddTester(int size) {
Foo foo = new foo(); //data structure
for(int i=0; i<size; i++){
foo.add(i);
if(!foo.isLegal())
return false;
return true;
}
However it is more complex and I'm trying to use streams to simplify and learn.
A way to do the same without using .peek()
is this: which does work - but I'm just "moving" the problem to .allMatch()
:
return IntStream.range(0, size).
.allMatch(i -> {
synchronized(r){foo.add(i)};
foo.isLegal();
)};
My problem is very similar to this question, the diffrence is that I am checking every time so the solutions aren't working.
So my questions are:
- Is
.peek()
really only to debugging or can I use it in this manner? - Is there any better solution?
- Should I use my second solution?
I'm looking for a correct solution, not a working solution, all of those codes are already working.