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

原文链接:Check if an item is contained in a stream

© 版权声明
THE END
喜欢就支持一下吧
点赞6 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容