[英]Copy List elements N times using Stream API
Is there a way to copy some List (or combined string if necessary) N times in Java using Stream API 有没有办法使用Stream API在Java中复制一些List(或必要时组合的字符串)N次
If the list consists of {"Hello", "world"}
and N = 3, the result should be {"Hello", "world", "Hello", "world", "Hello", "world"}
如果列表由
{"Hello", "world"}
和N = 3组成,则结果应为{"Hello", "world", "Hello", "world", "Hello", "world"}
What I've done so far is to get combined String element and I am not sure how to procees to copy it N times. 到目前为止我所做的是获得组合的String元素,我不知道如何进行N次复制。 While I can do it externally, I would like to see if it is possible to do with the help of streams
虽然我可以在外部进行,但我想看看是否可以使用流的帮助
Optional<String> sentence = text.stream().reduce((value, combinedValue) -> { return value + ", " + combinedValue ;});
I would like to use stream, because I am planning to continue with other stream operations after the one above 我想使用流,因为我计划继续上面的其他流操作
You can use Collections.nCopies
: 您可以使用
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>
This will product the List
: 这将产生
List
:
[Hello, World, Hello, World, Hello, World]
for your sample input. 为您的样本输入。
You can use an IntStream
and flatMap
to connect the text
List multiple times: 您可以使用
IntStream
和flatMap
多次连接text
List:
List<String> result = IntStream.range(0, 3)
.mapToObj(i -> text)
.flatMap(List::stream)
.collect(Collectors.toList());
The result looks like this: 结果如下:
[Hello, World, Hello, World, Hello, World]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.