I want to do something Initialize ArrayList with not null items, depending on its size from another variable.
private static final int SIZE_LIST_GROUP_MAP = 10;
public static final List<Map<String, String>> LIST_GROUP_MAP = new ArrayList<>() {
for(int i=0; i < SIZE_LIST_GROUP_MAP; i++)
{
add(new HashMap<>());
}
};
Is it possible to do something like that before?
If you are open to using a third-party library, this should work with Eclipse Collections:
public static final List<Map<String, String>> LIST_GROUP_MAP =
Lists.mutable.withNValues(SIZE_LIST_GROUP_MAP, HashMap::new);
Considering you are storing a mutable List
containing mutable Maps
in a static variable, you might want to consider using either a synchronized List
with synchronized or ConcurrentMap
s instead. The following code will give you a synchronized List
containing a fixed set of instances of ConcurrentMap
.
public static final List<Map<String, String>> LIST_GROUP_MAP =
Lists.mutable.<Map<String, String>>withNValues(
SIZE_LIST_GROUP_MAP,
ConcurrentHashMap::new).asSynchronized()
Eclipse Collections also has support for MultiReaderList
s.
public static final List<Map<String, String>> LIST_GROUP_MAP =
Lists.multiReader.withNValues(SIZE_LIST_GROUP_MAP, ConcurrentHashMap::new)
Finally, if the static List
will never change in size, then you can make it immutable as follows:
public static final ImmutableList<Map<String, String>> LIST_GROUP_MAP =
Lists.mutable.<Map<String, String>>withNValues(
SIZE_LIST_GROUP_MAP,
ConcurrentHashMap::new).toImmutable();
Note: I am a committer for Eclipse Collections.