Unchecked call to ifPresent inspection, why?

243 Views Asked by At

My code:

public static boolean searchLineOnLogFile(String...keywords)
{
    Collection select = null;

    try (final Stream<String> lines = Files.lines(get(getServerLog().toString())))
    {
        select = CollectionUtils.select(lines.collect(Collectors.toCollection(LinkedList::new)),
                new Predicate()
                {
                    public boolean evaluate(Object object)
                    {
                        String line = (String) object;
                        return Arrays.stream(keywords).allMatch(line::contains);
                    }
                });

    } catch (IOException e)
    {
        e.printStackTrace();
        Assert.fail(e.getMessage());
    }

    select.stream().findFirst().ifPresent(firstLine -> LogAutomation.info((String)firstLine));

    return select.size() > 0;
}    

select.stream().findFirst().ifPresent(firstLine -> log.info((String)firstLine));

Why I get 'uncheck call to isPresent' inspection ? how can I improve my code?

full inspection message

from what I 'v read all the idea is to avoid null check:

"So instead of writing something like:

if(optional.isPresent){
    doSomething(optional.get);
}

You can write:

optional.ifPresent(val->doSomething(val));

or if you prefer:

optional.ifPresent(this::doSomething);
2

There are 2 best solutions below

1
On

The warning is because the select can be null. Can be fixed by Optional.ofNullable

Optional.ofNullable(select).stream().findFirst().ifPresent(firstLine -> LogAutomation.info((String) firstLine));
0
On

You can use Optional.ofNullable, as answered by Butiri. You can also use Objects.requireNonNullElse.

With this second case you can define a default value if is empty. Example:

public class Main {

    public static void main(String[] args) {
        Collection<Integer> select = null;

        if (Math.random() > 0.5) {
            select = Arrays.asList(1, 2, 3);
        }

        Objects.requireNonNullElse(select, Collections.singletonList(99)).stream().
                findFirst().
                ifPresent(e -> System.out.println("found: " + e));
    }

}