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());
CopyTo(Stream, Int32) Reads the bytes from the current stream and writes them to another stream, using a specified buffer size.
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.
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]
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