DeinFreund DeinFreund - 3 months ago 8
Java Question

Instantiate List of objects with parameter array

I would like to instantiate a List of objects using an Array of parameters like so:

String[] winnerData = ("Team_1#Team_2#...#Team_N").split("#");
List<Team> winners = new ArrayList();
for (String w : winnerData){
winners.add(new Team(w));
}


How can I do this cleanly? Preferably in a single line.

I don't mind whether winners/winnerData is List or Array.

Answer

You can use the Stream API for such need.

String[] winnerData = ("Team_1#Team_2#...#Team_N").split("#");
// Create a Stream from the array of String
// For each String convert it as a Team using new Team(String)
// Convert the result as a List
List<Team> winners = Arrays.stream(winnerData)
    .map(Team::new)
    .collect(Collectors.toList());