Finding string in optional list of lists

user1178830 :

I have a list of 'Blocks' that could be null. Each of the blocks contains a list of names that also could be null. I'm trying to find if any of the names in all the blocks is the word "blurb".

I have the following code which does work:

private boolean containsText(List<Blocks> blocks) {
        return Optional.ofNullable(blocks)
            .map(Collection::stream)
            .map(o -> o.map(Blocks::getNames))
            .map(e -> e.anyMatch(names -> names != null && names.contains("blurb")))
            .orElse(false);
}

But since getNames could return null I have to check for it in the next statement. I could wrap it in another Optional at that point, but then I would end up with an Optional<Stream<Optional<List<String>>>>

Using names -> names != null seems cleaner? Or is there a way to simplify this?

Naman :

Another simpler variant without the use of Optional would just be :

private boolean containsText(List<Blocks> blocks) {
    return blocks != null && blocks.stream()
            .map(Blocks::getNames)
            .filter(Objects::nonNull)
            .anyMatch(list -> list.contains("blurb"));
}

Note: One of your problems is the design where you say, "I have a list of 'Blocks' that could be null", you should fix it to return an empty list for such representation and then get rid of the null check in the above code.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=8067&siteId=1