Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 310
Hatik Avatar asked Apr 03 '19 11:04

Hatik


1 Answers

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.

like image 193
Eran Avatar answered Sep 30 '22 12:09

Eran