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.
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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With