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

Format Decimal Numbers using Strings Within Pattern

As mentioned in earlier posts, the java.text.DecimalFormat class is used to format decimal numbers via predefined patterns specified as String. Apart from the decimal separator,...

Format Decimal Numbers Using Pattern

The java.text.DecimalFormat class is used to format numbers using a user specified formatting. This concrete subclass of NumberFormat, allows formatting decimal numbers via predefined...

Remove Duplicates from List Using LinkedHashSet

Another implementation of the Set interface is LinkedHashSet. LinkedHashSet maintains the order of elements and helps to overcome the HashSet limitation. The following code...

Â

MORE IN THIS CATEGORY

How To Concatenate Strings in Java

Introduction In Java, a String is a sequence of characters. There are often programming situations where you will need to concatenate Strings. There are several...

Maven CLI Options and Switches Reference

Maven offers a good set of commands and CLI Options to carry out wide range of Dev tasks. Most of these commands are in...

Java Tutorial #3 – Java Arrays

Table of Contents One Dimensional Array Declaring Array Allocting Memory to Array Accessing Array Elements Initializing Array Length of Array Multi Dimensional Array Creating 3...

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