Remove duplicates from list of integers using Lambda expression in Java
Java Lambda Program: Exercise-7 with Solution
Write a Java program to implement a lambda expression to remove duplicates from a list of integers.
Sample Solution:
Java Code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
// Create a list of integers with duplicates
List<Integer> nums = Arrays.asList(1, 2, 3, 3, 4, 3, 2, 5, 6, 1, 7, 7, 8, 10);
// Print the list
System.out.println("List elements " + nums);
// Remove duplicates using lambda expression
List<Integer> unique_nums = new ArrayList<>();
nums.stream()
.distinct()
.forEach(unique_nums::add);
// Print the list without duplicates
System.out.println("\nList elements without duplicates: " + unique_nums);
}
}
Sample Output:
List elements [1, 2, 3, 3, 4, 3, 2, 5, 6, 1, 7, 7, 8, 10] List elements without duplicates: [1, 2, 3, 4, 5, 6, 7, 8, 10]
Explanation:
In the above exercise we use the stream() method on the nums list to convert it into a stream. We call the distinct() method to filter out duplicate elements. The distinct() method ensures that only distinct elements are retained in the stream.
Finally, we use the forEach() method and a lambda expression unique_nums::add to add each unique element to the unique_nums list.
Flowchart:

Live Demo:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Java Lambda Exercises Previous: Calculate average of doubles using Lambda expression in Java.
Java Lambda Exercises Next: Calculate factorial using Lambda expression in Java.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
Java: Tips of the Day
Hashset vs Treeset:
HashSet is much faster than TreeSet (constant-time versus log-time for most operations like add, remove and contains) but offers no ordering guarantees like TreeSet.
HashSet
- the class offers constant time performance for the basic operations (add, remove, contains and size).
- it does not guarantee that the order of elements will remain constant over time
- iteration performance depends on the initial capacity and the load factor of the HashSet.
- It's quite safe to accept default load factor but you may want to specify an initial capacity that's about twice the size to which you expect the set to grow.
TreeSet
- guarantees log(n) time cost for the basic operations (add, remove and contains)
- guarantees that elements of set will be sorted (ascending, natural, or the one specified by you via its constructor) (implements SortedSet)
- doesn't offer any tuning parameters for iteration performance
- offers a few handy methods to deal with the ordered set like first(), last(), headSet(), and tailSet() etc
Important points:
- Both guarantee duplicate-free collection of elements
- It is generally faster to add elements to the HashSet and then convert the collection to a TreeSet for a duplicate-free sorted traversal.
- None of these implementations are synchronized. That is if multiple threads access a set concurrently, and at least one of the threads modifies the set, it must be synchronized externally.
- LinkedHashSet is in some sense intermediate between HashSet and TreeSet. Implemented as a hash table with a linked list running through it, however,it provides insertion-ordered iteration which is not same as sorted traversal guaranteed by TreeSet.
So a choice of usage depends entirely on your needs but I feel that even if you need an ordered collection then you should still prefer HashSet to create the Set and then convert it into TreeSet.
- e.g. SortedSet<String> s = new TreeSet<String>(hashSet);
Ref: https://bit.ly/3d3waGh
- Weekly Trends
- 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
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
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