I want to declare a fully populated map field in a single statement, (which may contain several nested statements,) like this:
private static final Map<Integer,Boolean> map =
something-returning-an-unmodifiable-fully-populated-HashMap;
Anonymous initializers won't do, for the same reason that invoking a function which returns a new populated map won't do: they require two top-level statements: one for the variable declaration, and one for the method or initializer.
The double curly bracket ({{ and }}) idiom will work, but it creates a whole new class which extends HashMap<>, and I do not like the overhead represented by this.
Do the lambdas of Java 8 perhaps offer a better way of accomplishing this?
Map, it doesn’t matter whether you writeType variable = expression;orType variable; { variable = expression; }. It will create exactly the same code.finalfields, the compiler will immediately shout, if someone removes the initializer or adds a second. However, if you think that’s too fragile, there is still nothing wrong with using a method. Then, the invocation is bound to the variable, when being used as an initializer, while the method should be named after what it creates, thus doesn’t need to be bound to the variable which uses it.