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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/lambda/java-lambda-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics