Java 8 Program to Remove Duplicate Elements from a List

1. Introduction

Removing duplicate elements from a collection is a common task in software development. Java 8 introduced the Stream API, which simplifies collection processing in a functional style. This blog post demonstrates how to use Java 8 Streams to remove duplicates from a list efficiently.

2. Program Steps

1. Create a list containing duplicate elements.

2. Use Java 8 Streams to filter out duplicates.

3. Collect the result into a new list.

4. Print both the original list and the list without duplicates to show the difference.

3. Code Program

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class RemoveDuplicates {
    public static void main(String[] args) {
        // Creating a list with duplicates
        List<Integer> numbersWithDuplicates = Arrays.asList(1, 2, 2, 3, 4, 4, 5, 6, 7, 7, 8, 9, 10);

        // Printing the original list
        System.out.println("Original list with duplicates: " + numbersWithDuplicates);

        // Removing duplicates using Stream API
        List<Integer> numbersWithoutDuplicates = numbersWithDuplicates.stream()
                                                                      .distinct() // Removing duplicates
                                                                      .collect(Collectors.toList()); // Collecting results into a list

        // Printing the list without duplicates
        System.out.println("List without duplicates: " + numbersWithoutDuplicates);
    }
}

Output:

Original list with duplicates: [1, 2, 2, 3, 4, 4, 5, 6, 7, 7, 8, 9, 10]
List without duplicates: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Explanation:

1. The program starts by importing the necessary classes from the java.util package for list handling and the java.util.stream package for stream processing.

2. A list named numbersWithDuplicates is created, containing integers with some duplicates.

3. The original list is printed to the console, showing the elements including duplicates.

4. To remove duplicates, the list is converted into a stream using the stream() method. The distinct() intermediate operation is then applied to filter out duplicate elements based on their equals() method.

5. The filtered stream is collected into a new list called numbersWithoutDuplicates using the collect() terminal operation, which takes Collectors.toList() as an argument to specify the desired collection type.

6. Finally, the program prints the new list without duplicates, demonstrating the effectiveness of using Streams for this purpose.

7. This example illustrates the power and simplicity of Java 8 Streams for processing collections, allowing for concise, readable, and declarative programming.

Comments