Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize an Optional<List<T>>? [closed]

It's fairly simple. I have a field for a list that may or may not be present (but that must be different from null as non-initialized), but while I can do

List<String> mylist = new ArrayList<>();

I cannot do

Optional<List<String>> mylist = Optional.of(new ArrayList<String>());

because the types don't match. This is unfortunate. I would not like to hard-wire my code to use ArrayList.

Is there a way around this?

like image 466
Antares42 Avatar asked Sep 14 '25 15:09

Antares42


2 Answers

I think the error is with your syntax.

This works for me.

Optional<List<String>> mylist = Optional.of(new ArrayList<String>());

Note the change of ; to the end of the line.

like image 86
Mike Murphy Avatar answered Sep 16 '25 06:09

Mike Murphy


The problem was not Java, it was my Maven project setup.

I had this in my pom.xml

    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>

which Eclipse then dutifully imported as Java Compiler -> JDK Compliance -> 1.7, and rightfully complained.

By setting this to 1.8 my code now compiles.

like image 37
Antares42 Avatar answered Sep 16 '25 05:09

Antares42