DeinFreund DeinFreund -4 years ago 138
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 Source

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 =
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download