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<>();

        // 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]


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: Java  Exercises: Check if string is empt.

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.

Follow us on Facebook and Twitter for latest update.