简体   繁体   中英

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

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.

You can use an IntStream and flatMap to connect the text List multiple times:

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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