SoaperGEM SoaperGEM - 1 month ago 8
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;
break;
}
}
}


As you would expect,
hashSetOfObjects
is of type
Set<MyObject>
where the class
MyObject
contains a method with signature
boolean customMethodReturnsBool(String entry)
. Also,
arrayOfStrings
is simply of type
String[]
.

Answer

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 = hashSetOfObjects.stream
                           .anyMatch(x -> arrayOfStrings.streams
                                            .anyMatch(y -> x.customMethodReturnsBool(y)));