Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Proper way of concatenating lists with single elements in a single logical line in Java?

In my code, I have this :

    private static final List<String> a = new ArrayList<String>() {{
        addAll(b);
        addAll(c);
        add(d);
        add(e);
    }};

I read in some places that the double-braces syntax creates an anonymous class or something and that it’s a very bad syntax.

As this is a static final variable, it needs to be set in a single logical line.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I found examples of code concatenating lists in a single line using a stream, but none that allow for individual elements to be added.

I’m looking for a syntax that would be compatible with Java 8, but (if different) a better syntax only compatible with later versions of Java would be welcome too.

>Solution :

There is no requirement for a static final variable to be initialized in a “single logical line”.

You can simply write

private static final List<String> a = new ArrayList<>();
static {
    a.addAll(b);
    a.addAll(c);
    a.add(d);
    a.add(e);
}

which is called a static initializer block.


Note that since this list will stay mutable the entire runtime, you can add to the list at any time and any place.

Since you probably do not want this, but rather a truly immutable list initialized with the class, you can even write

private static final List<String> a;
static {
    List<String> tmp = new ArrayList<>();
    tmp.addAll(b);
    tmp.addAll(c);
    tmp.add(d);
    tmp.add(e);
    a = List.copyOf(tmp);
}

in other words, assign the field at the end of the initializer block with the final result.

List.copyOf(…) (since Java 9) creates an immutable copy but does not allow null elements and has a very strict behavior regarding null in general.

If you need an unmodifiable list with null support, you can use tmp.stream().toList() (since Java 16).


But even for those who don’t know about static initializers, there is a very simple solution for complex field initializers:

private static final List<String> a = createA();

private static List<String> createA() {
    List<String> tmp = new ArrayList<>();
    tmp.addAll(b);
    tmp.addAll(c);
    tmp.add(d);
    tmp.add(e);
    return List.copyOf(tmp);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading