BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

How to remove duplicates from ArrayList in Java

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

In this tutorial, you will learn how to remove duplicates from ArrayList.

Example 1: Removing duplicates from ArrayList using LinkedHashSet

In the following example, we are removing the duplicate elements from ArrayList using LinkedHashSet. The steps followed in the program are:
1) Copying all the elements of ArrayList to LinkedHashSet. Why we choose LinkedHashSet? Because it removes duplicates and maintains the insertion order.
2) Emptying the ArrayList using clear() method.
3) Copying all the elements of LinkedHashSet(non-duplicate elements) to the ArrayList. Please find the source code below.

import java.util.ArrayList;
import java.util.List;
import java.util.LinkedHashSet;
public class RemoveDuplicates {

  public static void main(String[] args) {
 
     /* Creating ArrayList of Strings and adding
      * elements to it
      */
     List<String> al = new ArrayList<String>();
     al.add("Ajay");
     al.add("Becky");
     al.add("Chaitanya");
     al.add("Ajay");
     al.add("Rock");
     al.add("Becky");
 
     // Displaying ArrayList elements 
     System.out.println("Before:");
     System.out.println("ArrayList contains: "+al);
 
     // Creating LinkedHashSet
     LinkedHashSet<String> lhs = new LinkedHashSet<String>();
 
     /* Adding ArrayList elements to the LinkedHashSet
      * in order to remove the duplicate elements and 
      * to preserve the insertion order.
      */
     lhs.addAll(al);
  
     // Removing ArrayList elements
     al.clear();
 
     // Adding LinkedHashSet elements to the ArrayList
     al.addAll(lhs);
 
     // Displaying ArrayList elements
     System.out.println("After:");
     System.out.println("ArrayList contains: "+al);
  }
}

Output:

Before:
ArrayList contains: [Ajay, Becky, Chaitanya, Ajay, Rock, Becky]
After:
ArrayList contains: [Ajay, Becky, Chaitanya, Rock]

As you can see that the duplicates have been removed from the list and the insertion order is being preserved in the output.

Example 2: Removing duplicates using Iterator

In this example, we have an ArrayList that contain duplicate elements. We are iterating this ArrayList and adding the elements of it to a new list. We have placed a code inside iterating loop in such a way that if the element is already present in the new list, skip adding that element. This ensures that the new list is free from duplicate elements.

import java.util.*;
public class JavaExample {
  public static void main(String args[])
  {

    // Get the ArrayList with duplicate values
    ArrayList<Integer>
            arrList = new ArrayList<Integer>(
            Arrays.asList(10, 20, 20, 30, 30, 30, 50));

    // Print the Original ArrayList
    System.out.println("Original ArrayList: "+ arrList);

    // Creating a new ArrayList to store unique elements
    ArrayList<Integer> newList = new ArrayList<Integer>();

    // Iterating original ArrayList
    for (Integer element : arrList) {

      // Adding element to newList, if it contains the element
      // skip adding that element to not have duplicates
      if (!newList.contains(element)) {

        newList.add(element);
      }
    }

    // Print the ArrayList with duplicates removed
    System.out.println("ArrayList after removing duplicates: " + newList);
  }
}

Output:

Original ArrayList: [10, 20, 20, 30, 30, 30, 50]
ArrayList after removing duplicates: [10, 20, 30, 50]

Example 3: Removing duplicates using stream distinct()

In the following example, we are using the distinct() method of Stream API. This method removes the duplicates from the input stream and returns a new stream after removing duplicate elements.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class JavaExample
{
  public static void main(String[] args)
  {
    // Original ArrayList with duplicates
    ArrayList<Integer> arrList = new ArrayList<>(
            Arrays.asList(10, 20, 20, 30, 30, 30, 50));
    // Print the Original ArrayList
    System.out.println("ArrayList with duplicates: "+ arrList);

    // Creating a newList after applying the stream distinct() method
    // on the original ArrayList to remove duplicates
    List<Integer> newList = arrList.stream().distinct()
            .collect(Collectors.toList());

    // Printing ArrayList after removing duplicates
    System.out.println("ArrayList after removing duplicates: "+ newList);
  }
}

Output:

ArrayList with duplicates: [10, 20, 20, 30, 30, 30, 50]
ArrayList after removing duplicates: [10, 20, 30, 50]

Recommended Articles:

  • Convert Array to ArrayList
  • How to find length of ArrayList
  • ArrayList vs LinkedList
❮ Java Collections

Top Related Articles:

  1. How to loop HashMap in java
  2. Add Multiple Items to an ArrayList in Java
  3. Java 9 – @SafeVarargs Annotation (with examples)
  4. Java 8 Interface Changes – default method and static method
  5. Difference between ArrayList and Vector in Java

Tags: Collections, Java-ArrayList

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. yogesh says

    October 24, 2014 at 10:30 AM

    How to check whether the ArrayList contains un-ordered element or not with an in-build method?
    eg.
    Suppose i have a strings as “ABC” and “BCA”
    and if i check this ans should be true!

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap