Java Streams Distinct

1. Introduction

Java Streams introduced in Java 8 have significantly improved the way Java developers work with collections of data by providing a more functional approach to processing sequences of elements. One of the common operations while working with streams is removing duplicates from a collection, which can be efficiently achieved using the distinct() operation provided by the Stream API. This operation returns a stream consisting of the distinct elements of the original stream, based on the equals() method of the elements. This blog post will demonstrate how to use the distinct() operation to remove duplicates from a list of elements.

2. Program Steps

1. Create a list of elements with duplicates.

2. Convert the list to a stream.

3. Apply the distinct() operation to filter out duplicate elements.

4. Collect the results back into a list or another suitable collection.

5. Display the distinct elements.

3. Code Program

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

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

        // Step 2 and 3: Converting to stream and applying distinct()
        List<Integer> distinctNumbers = numbersWithDuplicates.stream()
                                                             .distinct()
                                                             .collect(Collectors.toList());

        // Step 4 and 5: Collecting the results and displaying them
        System.out.println("Original list with duplicates: " + numbersWithDuplicates);
        System.out.println("List after removing duplicates: " + distinctNumbers);
    }
}

Output:

Original list with duplicates: [1, 2, 3, 2, 4, 4, 5, 5, 6]
List after removing duplicates: [1, 2, 3, 4, 5, 6]

Explanation:

1. The program starts by defining a List<Integer> named numbersWithDuplicates that contains a series of integers, some of which are duplicated.

2. The list is converted to a stream using the .stream() method. Streams in Java allow for functional-style operations on collections of objects, such as filtering, mapping, or reducing.

3. The distinct() operation is then applied to the stream. This operation filters out duplicate elements based on their equals() method, ensuring that only unique elements are retained.

4. The stream of distinct elements is collected back into a List<Integer> using Collectors.toList(). This step gathers all the elements from the stream into a new list.

5. Finally, the original list and the list of distinct elements are printed. The output clearly shows that the duplicates from the original list were successfully removed by the distinct() operation, demonstrating an efficient way to remove duplicates from a collection using Java Streams.

Comments