Java Program: Remove Duplicate Elements from List using Streams
Java Stream: Exercise-4 with Solution
Write a Java program to remove all duplicate elements from a list using streams.
Sample Solution:
Java Code:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List < Integer > nums = Arrays.asList(10, 23, 22, 23, 24, 24, 33, 15, 26, 15);
System.out.println("Original List of numbers: " + nums);
// Remove duplicates
List < Integer > distinctNumbers = nums.stream()
.distinct()
.collect(Collectors.toList());
System.out.println("After removing duplicates from the said list: " + distinctNumbers);
}
}
Sample Output:
Original List of numbers: [10, 23, 22, 23, 24, 24, 33, 15, 26, 15] After removing duplicates from the said list: [10, 23, 22, 24, 33, 15, 26]
Explanation:
In the above exercise,
- The list of numbers is defined as nums and initialized with the Arrays.asList method.
- The distinct method is applied to the stream of numbers using the stream method on the nums list.
- This operation removes duplicate elements from the stream.
- The resulting stream is collected back into a list using the collect method with Collectors.toList().
Flowchart:

Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Sum of Even and Odd Numbers in a List using Streams.
Next: Count Strings Starting with Specific Letter using Streams.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
Converts a string from camelcase:
public static String fromCamelCase(String input, String separator) { return input .replaceAll("([a-z\\d])([A-Z])", "$1" + separator + "$2") .toLowerCase(); }
Ref: https://bit.ly/3u09A9E
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook