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

Hat*_*tik 5 java list java-stream

有没有一种方法可以使用Stream API在Java中复制某些列表(或必要时组合字符串)N次

如果该列表包含{"Hello", "world"}并且N = 3,则结果应为{"Hello", "world", "Hello", "world", "Hello", "world"}

到目前为止,我要做的是合并String元素,但我不确定如何将其复制N次。虽然我可以在外部进行操作,但是我想看看是否有可能借助流来完成

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

我想使用流,因为我计划在上述操作之后继续进行其他流操作

Era*_*ran 6

您可以使用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>
Run Code Online (Sandbox Code Playgroud)

这将产生List

[Hello, World, Hello, World, Hello, World]
Run Code Online (Sandbox Code Playgroud)

为您的样本输入。