Return a value from paralell stream? java

I have a method that uses parallelStream to run through an ArrayList of objects checking for collisions, however I'm not sure how to return a value from this sort of lambda expression inside the forEach() method. Is it impossible?

public static boolean isColliding(Ship moveingShip){

    Rectangle2D testRect = moveShip.getContainer(); //gets the rectangle to test

    GameManager.getArrayList().parallelStream().forEach((pS) ->
                               {if(testRect.intersects(pS.getContainer())) {//return boolean}});

    return //true or false depending on whether any collisions were detected
}

I don't think the forEach method has a return type, so I'm kinda stuck. Is there an alternative way of doing this besides reverting back to sequential forEach loops? The point of using parallel stream was to hopefully get through the ArrayList faster. Thanks.

Jon Skeet
people
quotationmark

If you're just trying to check whether any value matches the predict, you can use anyMatch:

Returns whether any elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then false is returned and the predicate is not evaluated.

This is a short-circuiting terminal operation.

So in your case:

return GameManager
    .getArrayList()
    .parallelStream()
    .anyMatch(pS -> testRect.intersects(pS.getContainer()));

In general, I'd suggest looking down the Stream and Collectors documentation. My experience with LINQ in .NET - not exactly the same, but similar - is that data processing like this works best when you think in terms of transformations and aggregations; forEach is always a sort of "last resort" when you just want to take an action on each value, rather than getting a result.

people

See more on this question at Stackoverflow