Write a Java program using Lambda Expression to remove duplicates from a list of integers


The java program that removes duplicate elements from a list of integers and then displays both the original list and the list with duplicates removed. However, there's a more efficient way to remove duplicates from a list in Java using Java Streams and the distinct operation. Here's an explanation of the code:

  • import java.util.ArrayList;, import java.util.Arrays;, and import java.util.List; : These lines import necessary classes for working with lists and arrays.
  • The RemoveDuplicate class is defined, which contains the main method, where the program's execution begins.
  • Inside the main method:
    • List<Integer> numbers = Arrays.asList(1, 2, 3, 2, 4, 5, 1, 6, 4);: This line creates a list of integers named numbers with duplicate values.
    • List<Integer> distnum = new ArrayList<>(numbers); : This line creates a new ArrayList named distnum and initializes it with the elements from the numbers list. This is done to preserve the original list.
    • distnum.removeIf(number -> numbers.indexOf(number) != numbers.lastIndexOf(number));: This line uses the removeIf method to remove elements from distnum if the first occurrence of the element (as determined by indexOf) is not the same as the last occurrence (as determined by lastIndexOf). This effectively removes duplicates from distnum.
    • System.out.println("Original Numbers : " + numbers);: This line prints the original list of numbers.
    • System.out.println("Distinct Numbers : " + distnum);: This line prints the list of numbers with duplicates removed.

Source Code

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 
public class RemoveDuplicate
{
	public static void main(String[] args)
	{
		List<Integer> numbers = Arrays.asList(1, 2, 3, 2, 4, 5, 1, 6, 4);
 
		List<Integer> distnum = new ArrayList<>(numbers);
		distnum.removeIf(number -> numbers.indexOf(number) != numbers.lastIndexOf(number));
 
		System.out.println("Original Numbers : " + numbers);
		System.out.println("Distinct Numbers : " + distnum);
	}
}

Output

Original Numbers : [1, 2, 3, 2, 4, 5, 1, 6, 4]
Distinct Numbers : [3, 5, 6]

Example Programs