Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat Stream allMatch() until true

Tags:

java

java-8

int testValue;
boolean success = false;

while(success == false) {
 testValue = generateRandomInt();   
 success = mySystem.getHosts().parallelStream().allMatch(predicate(testValue));
}

return testValue;

I am playing around with java8 streams. What do you suggest to make the code above more elegant/readable?

like image 501
Moonlit Avatar asked May 29 '17 11:05

Moonlit


People also ask

What is stream allMatch?

Stream allMatch(Predicate predicate) returns whether all elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result. This is a short-circuiting terminal operation.

What is LIST stream Java?

A stream consists of source followed by zero or more intermediate methods combined together (pipelined) and a terminal method to process the objects obtained from the source as per the methods described. Stream is used to compute elements as per the pipelined methods without altering the original value of the object.


1 Answers

You can use an infinite IntStream instead of the while loop, and return the first int of the stream that matches your condition:

return IntStream.generate (() -> generateRandomInt())
                .filter (i -> mySystem.getHosts().parallelStream().allMatch(predicate(i)))
                .findFirst()
                .getAsInt();
like image 181
Eran Avatar answered Oct 05 '22 23:10

Eran