Search code examples
javalistjava-stream

How can I duplicate each item in a Java list using a stream?


I need to duplicate items in a List.

So, if the list is:

["firstItem", "secondItem"]

I want to return a list that is:

["firstItem","firstItem","secondItem","secondItem"]

I'm trying to do this through the flatMap function but I'm not sure how to go about doing it.

List<T> duplicatedList = originalList.stream()
            .flatMap(u -> Stream.of()) // how to duplicate items??
            .collect(Collectors.toList());

Solution

  • Create a Stream of two identical items :

    List<String> originalList = Arrays.asList("firstItem","secondItem");
    List<String> duplicatedList = originalList.stream()
            .flatMap(u -> Stream.of(u,u))
            .collect(Collectors.toList());
    System.out.println(duplicatedList);
    

    Output :

    [firstItem, firstItem, secondItem, secondItem]