How To Remove Duplicate Elements From an ArrayList In Java?

In This Tutorial we will learn How To Remove Duplicate Elements From An ArrayList In java.

Steps needs to be followed to Remove duplicate elements from an Arraylist in java.

  • create an ArrayList Object and add elements to the ArrayList which includes Duplicate elements.
  • Now create Linkedhashset instance and copy all the elements of ArrayList To LinkedHashSet. Here one point to note why we are choosing LinkedHashSet,because LinkedHashSet removes the duplicate elements and it follows Insertion order.
  • Now empty the arraylist object by calling clear() method.and then Copying all the elements of LinkedHashSet To The ArrayList That,s can see the below code.


package com.practice;

import java.util.ArrayList;
import java.util.LinkedHashSet;

public class RemveDupArrayList {

public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> arraylist = new ArrayList<Integer>();

System.out.println("ArrayList before removing duplicate values:"+arraylist);

LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<Integer>(arraylist);


System.out.println("ArrayList after clearing all values :"+arraylist);

ArrayList<Integer> arrlist = new ArrayList<Integer>(linkedHashSet);

System.out.println("ArrayList After removing duplicate values :"+arrlist);




ArrayList before removing duplicate values:[10, 20, 30, 10, 40, 20]
ArrayList after clearing all values :[]
ArrayList After removing duplicate values :[10, 20, 30, 40]

No comments:

Post a Comment