0

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?

Naman
  • 27,789
  • 26
  • 218
  • 353

2 Answers2

1

You can do it with double braces, but you end up with a subclass of ArrayList:

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<>());  
    }
}};

Check this answer for more details: Efficiency of Java "Double Brace Initialization"?

1

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 ConcurrentMaps 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 MultiReaderLists.

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.

Donald Raab
  • 6,458
  • 2
  • 36
  • 44