繁体   English   中英

将嵌套循环转换为流 Java 8

[英]Convert nested loops into streams Java 8

我正在尝试将下面的嵌套循环转换为流 Java 8。

newself2中的每个元素都是一个字符串列表——["1 2","3 4"]需要改为["1","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 循环中的拆分数组添加到x的新列表中?

非常感谢任何帮助。

这是我的做法:

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

这是其他解决方案。

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());

with 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(",")));
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM