1. Introduction

When working with ArrayList in Java, you might encounter situations where the list contains duplicate elements, and you want to remove them. This tutorial will guide you on how to remove duplicate elements from an ArrayList using Java’s Stream API.

2. Program Steps

1. Create an ArrayList and populate it with some elements, including duplicates.

2. Print out the original ArrayList.

3. Utilize the distinct() method of the Stream API to filter out the duplicate elements.

4. Collect the result into a new ArrayList.

5. Print out the ArrayList after removing the duplicates.

3. Code Program

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

public class RemoveDuplicates {

    public static void main(String[] args) {

        // Step 1: Create an ArrayList and populate it with some elements, including duplicates
        List<String> arrayList = new ArrayList<>();
        arrayList.add("Java");
        arrayList.add("Python");
        arrayList.add("Java");
        arrayList.add("C++");
        arrayList.add("Python");

        // Step 2: Print out the original ArrayList
        System.out.println("Original ArrayList: " + arrayList);

        // Step 3: Utilize the distinct() method of the Stream API to filter out the duplicate elements
        // Step 4: Collect the result into a new ArrayList
        List<String> uniqueList = arrayList.stream().distinct().collect(Collectors.toList());

        // Step 5: Print out the ArrayList after removing the duplicates
        System.out.println("ArrayList after removing duplicates: " + uniqueList);
    }
}

Output:

Original ArrayList: [Java, Python, Java, C++, Python]
ArrayList after removing duplicates: [Java, Python, C++]

4. Step By Step Explanation

Step 1: An ArrayList named arrayList is initialized and populated with some elements, including duplicates like "Java" and "Python".

Step 2: The content of the original ArrayList is printed to the console, showing the elements with duplicates: "Original ArrayList: [Java, Python, Java, C++, Python]".

Step 3: The distinct() method of the Stream API is used to filter out the duplicate elements from arrayList. The distinct() method returns a stream consisting of the distinct elements according to their natural order or by the comparator provided at creation time, if any.

Step 4: The collect() method of the Stream API is used with Collectors.toList() to gather the distinct elements into a new ArrayList named uniqueList.

Step 5: The content of the ArrayList uniqueList is printed to the console, showing the elements after removing the duplicates: "ArrayList after removing duplicates: [Java, Python, C++]".