1

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);
        }
    }
Naman
  • 27,789
  • 26
  • 218
  • 353
babastyle
  • 53
  • 1
  • 10
  • 1
    Define “efficient”. If you mean “performance”, it’s as fast as it can be unless you want to introduce multiple threads. Or do you mean “minimum code” or “elegant code”? – Bohemian Mar 14 '20 at 21:50
  • maybe something with the same performance but more "elegant" – babastyle Mar 14 '20 at 21:52

1 Answers1

2

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]
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110