将嵌套循环转换为流 Java 8

问题描述 投票:0回答:3

我正在尝试将下面的嵌套循环转换为 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
的新列表中?

非常感谢任何帮助。

java loops java-8 java-stream
3个回答
8
投票

我的做法是这样的:

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

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

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

0
投票

将列表更改为具有许多内部列表的流java。

首先使用 .map(),然后使用 forEach() 来更改属性。

    List<SquadCardDto> sqaurdList = guardCardDto.getSquads().stream().map(
            outerDto -> {
                OuterDto newOuterDto = modelMapper.map(outerDto, OuterDto.class);
                outerDto.getInnerList.stream().forEach(
                        innerListDto -> {
                            Boolean newValueAttribute = Boolean.FALSE;
                            innerListDto.setAttribute(newValueAttribute);
                            //some code where change condition of 
                        }
                );
                return newOuterDto;
            }
    ).collect(Collectors.toList());
    
© www.soinside.com 2019 - 2024. All rights reserved.