将嵌套循环转换为Java 8流

时间:2018-04-10 01:02:23

标签: loops java-8 java-stream

我正在尝试将以下嵌套循环转换为流Java 8.

newself2中的每个元素都是字符串列表 - [" 1 2"," 3 4"]需要更改为[" 1",&# 34; 2"" 3"" 4"。]

for (List<String> list : newself2) {
    // cartesian = [["1 2","3 4"],["4 5","6 8"]...] list = ["1 2","3 4"]...
    List<String> clearner = new ArrayList<String>();
    for (String string : list) { //string = "1 3 4 5"
        for (String stringElement : string.split(" ")) {
            clearner.add(stringElement);
        }
    }
    newself.add(clearner);
    //[["1","2","3","4"],["4","5","6","8"]...]
}

到目前为止我一直在尝试 -

newself2.streams().forEach(list -> list.foreach(y -> y.split(" ")))  

现在我现在确定如何将内部for循环中的split数组添加到x的新列表中?

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:4)

我是这样做的:

List<List<String>> result = newself2.stream()
    .map(list -> list.stream()
            .flatMap(string -> Arrays.stream(string.split(" ")))
            .collect(Collectors.toList()))
    .collect(Collectors.toList());

答案 1 :(得分:1)

这是其他解决方案。

Function<List<String>,List<String>> function = list->Arrays.asList(list.stream()
            .reduce("",(s, s2) -> s.concat(s2.replace(" ",",")+",")).split(","));

并使用此功能

 List<List<String>> finalResult = lists
                                 .stream()
                                 .map(function::apply)
                                 .collect(Collectors.toList());
带有for循环的

与此类似:

  List<List<String>> finalResult = new ArrayList<>();
    for (List<String> list : lists) {
        String acc = "";
        for (String s : list) {
            acc = acc.concat(s.replace(" ", ",") + ",");
        }
        finalResult.add(Arrays.asList(acc.split(",")));
    }