Site icon Automation Dojos

Remove Duplicates from List Using Stream

Java 8 has added the Stream API that helps to easily perform bulk operations on Collections. A new method called stream() method has been added to all the collection interfaces that returns a Stream corresponding to the underlying collection. The Stream interface has a method called distinct that can be used to eliminate duplicates. The following code demonstrates this:

Here, first the stream() method is invoked on the input List. This returns a Stream corresponding to the List. Then the distinct() method is invoked on the Stream. This returns a new Stream that has only the unique elements from the input List. Finally, the collect() method is invoked which converts the Stream to a List back. So this code prints the following output:
5 10 15 20 35 40 25

Exit mobile version