繁体   English   中英

使用Stream API将列表元素复制N次

[英]Copy List elements N times using Stream API

有没有办法使用Stream API在Java中复制一些List(或必要时组合的字符串)N次

如果列表由{"Hello", "world"}和N = 3组成,则结果应为{"Hello", "world", "Hello", "world", "Hello", "world"}

到目前为止我所做的是获得组合的String元素,我不知道如何进行N次复制。 虽然我可以在外部进行,但我想看看是否可以使用流的帮助

Optional<String> sentence = text.stream().reduce((value, combinedValue) -> { return value + ", " + combinedValue ;});

我想使用流,因为我计划继续上面的其他流操作

您可以使用Collections.nCopies

List<String> output =
    Collections.nCopies(3,text) // List<List<String>> with 3 copies of 
                                // original List
               .stream() // Stream<List<String>>
               .flatMap(List::stream) // Stream<String>
               .collect(Collectors.toList()); // List<String>

这将产生List

[Hello, World, Hello, World, Hello, World]

为您的样本输入。

您可以使用IntStreamflatMap多次连接text List:

List<String> result = IntStream.range(0, 3)
        .mapToObj(i -> text)
        .flatMap(List::stream)
        .collect(Collectors.toList());

结果如下:

[Hello, World, Hello, World, Hello, World]

暂无
暂无

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

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