-2

Is it possible to combine the creation of a List of String[] with the initialization of the first entry in the List?

final List<String[]> rolesCsv = new ArrayList<String[]>();
rolesCsv.add(new String[] {"Role Name","Description"});

In other words, can I combine the above two lines into a single one that both creates and initializes the List?

The List<String[]> does need to be mutable for later adding to the List, yes.

IMPORTANT NOTE for EDITORS: Creating and initializing this definition is far different than solutions for simply creating and initializing List<String>- BEFORE you automatically link this question to the common answers for the latter, please stop! The problem is different and requires a different solution.

Kim Gentes
  • 1,496
  • 1
  • 18
  • 38
  • Does it need to be an ArrayList or can it be any kind of list? Does it need to be mutable? – khelwood Jul 27 '21 at 17:11
  • @user16320675 yes... thank you ! You should post this as the answer, since all other answers posted elsewhere only deal with atomic types inside a list (such as List)... thanks for your excellent answer. – Kim Gentes Jul 27 '21 at 17:26
  • @stdunbar points to the right question, and probably [you need this answer in particular](https://stackoverflow.com/a/3676539/10621296), the one with the header "If you specifically need a java.util.ArrayList" – Jetto Martínez Jul 27 '21 at 17:31
  • In general, you don't want to mix arrays and `List`s. Why not a `List>`? – MC Emperor Jul 27 '21 at 18:58

2 Answers2

0

The correct answer was given in the comments (above) by @user16320675 , and this works well. It handles both the creation of the outer List and the internal array of strings. Other answers pointing to a simple Array asList are for simple strings, which is not the question that was asked.

to create a mutable list

final List<String[]> rolesCsv =
     new ArrayList<String[]>Collections.singletonList(new String[]{"Role Name","Description"}));

Otherwise (despite the array, its element, will not be immutable)

final List<String[]> rolesCsv =
      Collections.singletonList(new String[]{"Role Name","Description"})
Kim Gentes
  • 1,496
  • 1
  • 18
  • 38
-1

List<String> sameline = Arrays.asList("1", "2", "3");

This is the way to Create and initialize Java List in the same line.