Skip to main content

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]

Popular posts from this blog

Java Primitive DataTypes

Java data types will tell us what type of data can variable hold. Ex: int x = 10; In the above variable, x can hold int data type value.so we must declare any variable with data type before we can use a variable.

Instance Variables in Java

Instance variables should declare with in the class but outside of any method or block or constructor.instance variables can accessible inside class all methods , blocks & constructors.

Angular 9 Date Pipe Example

Table of Contents what is pipe in angular? Angular Date Pipe Pre-defined Date Format Custom Date Formats what is pipe in angular? In Angular Pipes are used to transform data.Pipes will take input data and transforms input data in desired output. Symbol of Pipe : " | " Angular Date Pipe Angular DatePipe is one of built-in Pipes.DatePipe is used for Format a date value according to locale rules. Syntax {{value_expression| date [:format[:timezone[:locale]]]}} DatePipe avalibale in '@angular/common' module. Example //app.component.ts import   {   Component   }   from   '@angular/core' ; @ Component ({   selector:   'app-root',    template:   `{{dOB | date:'fullDate'}}`,    styleUrls:  ['./app.component.css'] }) expo...