w3resource

Remove duplicates from list of integers using Lambda expression in Java


Remove Duplicates from List of Integers

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:

Flowchart: Java  Exercises: Check if string is empt.

For more Practice: Solve these Related Problems:

  • Write a Java program to implement a lambda expression that removes duplicates and then sorts the resulting list in ascending order.
  • Write a Java program to create a lambda that filters out duplicate integers and then computes the sum of the unique values.
  • Write a Java program to implement a lambda that removes duplicates from a list of integers and returns the count of unique elements.
  • Write a Java program to use a lambda expression with a distinct() operation to remove duplicates and then convert the list to a set.

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.