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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With