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 it.you can see the below code.

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>();
arraylist.add(10);
arraylist.add(20);
arraylist.add(30);
arraylist.add(10);
arraylist.add(40);
arraylist.add(20);

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


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

arraylist.clear();

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);



}

}

output:


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