Java 8 Find Duplicates in List

In this quick tutorial, I show you how to find duplicates in List in Java. We will see first using plain Java and then Java 8 Lambda-based solution.

Remove Duplicates from a List Using Plain Java

Removing the duplicate elements from a List with the standard Java Collections Framework is done easily through a Set:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

/**
 * Remove Duplicates from a List Using Java
 * @author Ramesh Fadatare
 *
 */
public class FindDuplicatesInList {

    public static void main(String[] args) {
        List < Integer > listWithDuplicates = Arrays.asList(0, 1, 2, 3, 0, 0);

        List < Integer > listWithoutDuplicates = new ArrayList < > (
            new HashSet < > (listWithDuplicates));

        listWithoutDuplicates.forEach(element -> System.out.println(element));
    }
}
Output:
0
1
2
3

Remove Duplicates from a List Using Java 8 Lambdas

Let's look at a new solution, using Lambdas in Java 8; we're going to use the distinct() method from the Stream API which returns a stream consisting of distinct elements based on the result returned by equals() method:
package net.javaguides.jackson;

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

/**
 * Remove Duplicates from a List Using Java
 * @author Ramesh Fadatare
 *
 */
public class FindDuplicatesInList {

    public static void main(String[] args) {
        List < Integer > listWithDuplicates = Arrays.asList(0, 1, 2, 3, 0, 0);

        List < Integer > listWithoutDuplicates = listWithDuplicates.stream()
            .distinct()
            .collect(Collectors.toList());

        listWithoutDuplicates.forEach(element -> System.out.println(element));

    }
}
Output:
0
1
2
3

Related Java 8 Articles

Comments