DEV Community

taijidude
taijidude

Posted on

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)