Check duplicate in list java 8

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 listWithDuplicates = Arrays.asList[0, 1, 2, 3, 0, 0]; List 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 listWithDuplicates = Arrays.asList[0, 1, 2, 3, 0, 0]; List listWithoutDuplicates = listWithDuplicates.stream[] .distinct[] .collect[Collectors.toList[]]; listWithoutDuplicates.forEach[element -> System.out.println[element]]; } }
Output:
0 1 2 3

Related Java 8 Articles

  • Java 8 Lambda Expressions
  • Java 8 Functional Interfaces
  • Java 8 Method References
  • Java 8 Stream API
  • Java 8 Optional Class
  • Java 8 Collectors Class
  • Java 8 StringJoiner Class
  • Java 8 Static and Default Methods in Interface
  • Factory Pattern Using Java 8 Lambda Expressions
  • Java 8 - Merging Two Maps Example
  • Java 8 Convert List to Map Example
  • Guide to Java 8 forEach Method
  • Handle NullPointerException using Java 8 Optional Class
  • How to Use Java 8 Stream API in Java Projects
  • Migrating Source Code to Java 8
  • Refactoring Observer Design Pattern with Lambdas
  • Refactoring Strategy Design Pattern with Lambdas
  • Refactoring Chain of Responsibility Pattern with Lambdas
Core Java Examples Java 8

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours

Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Video liên quan

Chủ Đề