SoaperGEM SoaperGEM - 1 year ago 61
Java Question

How can I simplify these nested for loops with collectors in Java 8?

I'm very new to the idea of collectors and parallel streams in Java, and am wondering if there's a way to simplify this code:

boolean foundAnyMatch = false;
for (MyObject myObject : hashSetOfObjects) {
for (int i = 0; i < arrayOfStrings.length; i++) {
if (myObject.customMethodReturnsBool(arrayOfStrings[i])) {
foundAnyMatch = true;

As you would expect,
is of type
where the class
contains a method with signature
boolean customMethodReturnsBool(String entry)
. Also,
is simply of type

Answer Source

As per my understanding, your code runs for O(n) times on hashSetOfObjects. While your intention is to find if any object in hashSetOfObjects results truly in nested code. Same logic can be represented using streams as:

boolean foundAnyMatch =
                           .anyMatch(x -> arrayOfStrings.streams
                                            .anyMatch(y -> x.customMethodReturnsBool(y)));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download