Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate items in a stream in java

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());
like image 821
Talal Nabulsi Avatar asked Jul 12 '16 09:07

Talal Nabulsi


People also ask

What is the function used to duplicate a stream?

CopyTo(Stream, Int32) Reads the bytes from the current stream and writes them to another stream, using a specified buffer size.

How do I filter duplicates in stream?

You can use the Stream. distinct() method to remove duplicates from a Stream in Java 8 and beyond. The distinct() method behaves like a distinct clause of SQL, which eliminates duplicate rows from the result set.


1 Answers

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]
like image 109
Eran Avatar answered Sep 28 '22 06:09

Eran