babastyle :
I don't really feel comfortable with the following code, but I don't know how to implement it in a more efficient way.
List<String> words = new ArrayList<String>();
for (String line : newList) {
String[] lineArray = line.split(" ");
for (String l : lineArray) {
words.add(l);
}
}
Arvind Kumar Avinash :
An elegant way would be as follows:
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);
}
}
Output:
[Amitabh, Bachchan, James, Bond, Kishore, Kumar, Arvind, Kumar, Avinash]
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=276782&siteId=1