How do I initialize an Optional<List<T>>?

10,977

Solution 1

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.

Solution 2

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.

Share:
10,977
Antares42
Author by

Antares42

Jack of all trades: Programmer (Java, JS, PHP, R, Matlab, Scala...) "All that other stuff" (Databases, servers, security) Researcher (Physics, MSc, and Medical biochemistry, PhD) Language enthusiast (German, English, Norwegian; Italian, French, Latin, Chinese)

Updated on August 31, 2022

Comments

  • Antares42
    Antares42 over 1 year

    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?