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?
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With