DEV Community

taijidude
taijidude

Posted on

1

Check if an item is contained in a stream

I recently tried to filter trough a stream to check if a specific item was present. My first approach was the following:


return customers
            .stream()
            .filter(customer -> customer.getName().equals("Smith"))
            .findFirst()
            .isPresent();


Enter fullscreen mode Exit fullscreen mode

But in my company uses sonar qube (https://www.sonarqube.org/) as a static code analysis tool. SQ suggested me a better solution for this:

return customers
        .stream()
        .anyMatch(
            customer -> customer.getName().equals("Smith")
        );

Enter fullscreen mode Exit fullscreen mode

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay