Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 290
DeinFreund Avatar asked Dec 15 '22 04:12

DeinFreund


2 Answers

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());
like image 141
Nicolas Filotto Avatar answered Dec 28 '22 05:12

Nicolas Filotto


You might want to consider skipping intermediate array creation using Pattern.splitAsStream:

// Declare the pattern somewhere in the appropriate class
static final Pattern DELIMITER = Pattern.compile("#");

String winnerData = "Team_1#Team_2#...#Team_N";
List<Team> winners = DELIMITER.splitAsStream(winnerData)
    .map(Team::new)
    .collect(Collectors.toList());

This way the intermediate array is not created making the whole chain completely lazy which may take less memory (and work faster) if you have many teams.

like image 36
Tagir Valeev Avatar answered Dec 28 '22 06:12

Tagir Valeev