【问题标题】:split list of string lines and add words to a new list [duplicate]拆分字符串行列表并将单词添加到新列表[重复]
【发布时间】:2020-03-14 21:41:52
【问题描述】:

我对下面的代码不太满意,但我不知道如何以更有效的方式实现它。

    List<String> words = new ArrayList<String>();
    for (String line : newList) {
        String[] lineArray = line.split(" ");
        for (String l : lineArray) {
            words.add(l);
        }
    }

【问题讨论】:

  • 定义“高效”。如果您的意思是“性能”,那么除非您想引入多个线程,否则它会尽可能快。还是您的意思是“最小代码”或“优雅代码”?
  • 也许性能相同但更“优雅”

标签: java list algorithm split java-stream


【解决方案1】:

一种优雅的方式如下:

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]

【讨论】:

    猜你喜欢
    • 2018-07-15
    • 1970-01-01
    • 2018-01-15
    • 2015-11-22
    • 2018-03-13
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多