我想使用参数数组实例化一个对象列表,如下所示:
String[] winnerData = ("Team_1#Team_2#...#Team_N").split("#");
List<Team> winners = new ArrayList();
for (String w : winnerData){
winners.add(new Team(w));
}
我怎样干净利落地做到这一点?最好是一行。
我不介意winners / winnerData是List还是Array。
答案 0 :(得分:5)
您可以使用Stream API
来满足此类需求。
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());
答案 1 :(得分:5)
您可能需要考虑使用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());
这样就不会创建中间数组,因为如果你有很多团队,那么整个链完全是懒惰的,这可能会占用更少的内存(并且工作更快)。