user0000001
user0000001

Reputation: 2233

Using parallel stream to find a single object in collection

Rather new to streams in Java, still getting the hang of it. I've seen a few examples but none of them seem to fit my use case.

I have a list of objects that can grow exponentially and I would like to parallelize the loop I'm using to find a single item in this list.

Here is what I currently have:

for (Node node : itemList)
{
    if (node.itemData().dataId() == searchData.itemData().dataId())
        return node;
}

return null;

Here is my attempt at a concurrent version of this loop

List<Node> nodeItem = itemList.parallelStream()
                              .filter(item -> item.itemData().dataId() == searchData.itemData().dataId())
                              .collect(Collectors.toList());

return (!nodeItem.isEmpty() ? nodeItem.get(0) : null);

There are two problems I am seeing here. The first one being that I am putting this single entry into a List. I understand that this is a result of collect() but I don't see any other way of collecting an individual item.

The other issue I see here is that the paralleled threads will continue working through their part of the list until they're finished iterating. I would prefer if each worker was signaled to end prematurely when the item is found.

Upvotes: 2

Views: 2545

Answers (1)

Jacob G.
Jacob G.

Reputation: 29680

As JB stated, you can use Stream#findAny, a terminal operation that will return an Optional of the element you're looking for.

return itemList.parallelStream()
               .filter(item -> item.itemData().dataId() == searchData.itemData().dataId())
               .findAny()
               .orElse(null);

Upvotes: 2

Related Questions