新しいリストに文字列ラインと追加の単語の分割リスト

babastyle:

私は実際に次のコードを使用して快適に感じることはありませんが、私は、より効率的な方法でそれを実装する方法がわかりません。

    List<String> words = new ArrayList<String>();
    for (String line : newList) {
        String[] lineArray = line.split(" ");
        for (String l : lineArray) {
            words.add(l);
        }
    }
アービンド・クマールのAvinash:

次のようにエレガントな方法は次のようになります。

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]

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=284177&siteId=1