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

Tushar Sharma
Tushar Sharmahttps://www.automationdojos.com
Hi! This is Tushar, the author of 'Automation Dojos'. A passionate IT professional with a big appetite for learning, I enjoy technical content creation and curation. Hope you are having a good time! Don't forget to subscribe and stay in touch. Wishing you happy learning!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

RELATED POSTS

Concatenate Strings Using String.concat()

The String class has a method called concat. It accepts as parameter a String value and concatenates it with the current String. The following...

Convert List to Array Using For-Loop

The simplest way to convert a List to an array is to use a for-loop. The following code snippet demonstrates this method. First, the code...

How To Remove Duplicates From List in Java

Introduction A List is an interface in the Java collection framework which can be used to store a group of objects. A List is ordered...

Â

MORE IN THIS CATEGORY

Early Bound Vs Late Bound (Binding)

What is Binding Before we dive into 'Early' and 'Late' stuff, let us discover, what the 'Binding' itself means? In simple terms, the 'Binding' refers to...

COM Components and Scripting Process

Although this article should not concern you at all as a 'script developer' as long as you are aware of creating a reference to...

How To Auto-launch VBscript with Elevated Privileges

For cases when you need to execute a VBS script (*.vbs file) as admin with elevated privileges you can try the following snippet. This...

RECENT 'HOW-TO'

How To Install Oh-My-Posh On Windows PowerShell

Oh-My-Posh is a powerful custom prompt engine for any shell that has the ability to adjust the prompt string with a function or variable. It does not...

SIMILAR ON CODEX

- Advertisement -spot_img