In this tutorial, we will see “How to remove duplicates from ArrayList using Java 8”. In order to remove duplicates from the list, we are going to use Stream API introduced in Java 8.

Remove duplicates from ArrayList using Java 8 Stream API...!!! Share on X

Example

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

public class RemoveDuplicatesFromListJava8 {

    public static void main(String[] args) {

        List <String> originalList = new ArrayList <String> ();

        originalList.add("yogi");
        originalList.add("noni");
        originalList.add("isha");
        originalList.add("yogi");
        originalList.add("pulkit");
        originalList.add("noni");
        originalList.add("noni");

        System.out.println("Original List: \n" + originalList);

        List <String> listAfterDuplicatesRemoval = list.stream()
            .distinct()
            .collect(Collectors.toList());

        System.out.println("\nList after duplicates removal: \n" + listAfterDuplicatesRemoval);
    }

}

 

Let’s try to understand the code:

1. Create a list and add duplicate elements into it. 

List < String > list = new ArrayList < String > ();

        list.add("yogi");
        list.add("noni");
        list.add("isha");
        list.add("yogi");
        list.add("pulkit");
        list.add("noni");
        list.add("noni");

 

2. Convert the list into ‘stream’

list.stream()

 

3. Extract the unique entries in the list with the use of ‘distinct’ method of stream

list.stream()
            .distinct()

 

4. Finally, Store the unique or distinct entries in to a collector

collect(Collectors.toList())

 

Output:

Original List: 
[yogi, noni, isha, yogi, pulkit, noni, noni]

List after duplicates removal: 
[yogi, noni, isha, pulkit]

 

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts