我对下面的代码不太满意,但我不知道如何以更有效的方式实现它。
List<String> words = new ArrayList<String>();
for (String line : newList) {
String[] lineArray = line.split(" ");
for (String l : lineArray) {
words.add(l);
}
}
最佳答案
一种优雅的方式如下:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] argv) throws Exception {
List<String> newList = List.of("Amitabh Bachchan", "James Bond", "Kishore Kumar", "Arvind Kumar Avinash");
List<String> words = newList.stream().flatMap(s -> Arrays.stream(s.split(" "))).collect(Collectors.toList());
System.out.println(words);
}
}
输出:
[Amitabh, Bachchan, James, Bond, Kishore, Kumar, Arvind, Kumar, Avinash]
关于java - 拆分字符串行列表并将单词添加到新列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60687563/