Is there a way to copy some List (or combined string if necessary) N times in Java using Stream API
If the list consists of {"Hello", "world"}
and N = 3, the result should be {"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. 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
:
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
:
[Hello, World, Hello, World, Hello, World]
for your sample input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With