Monday, 2 July 2012

Remove duplicate element in list - Java

Problem: Remove duplicate element in the list
Solution: Use set as flag to remove duplicate elements in the list
package com.lac;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

 * Employee bean
class Employee {
 private int id;
 private String name;

 public Employee(int id, String name) {
  super(); = id; = name;

 public int getId() {
  return id;

 public void setId(int id) { = id;

 public String getName() {
  return name;

 public void setName(String name) { = name;


 * Remove Duplicates in list
public class RemoveDuplicates {
 public static void main(String[] args) {
  //Create Employee objects
  Employee a= new Employee(1, "Jhon");
  Employee b= new Employee(2, "Jane");
  Employee c= new Employee(3, "King");
  List list= new ArrayList();
  list.add(a);list.add(b);list.add(c); //add employees
  list.add(b);//add duplicate employee
  final Set empIds= new HashSet();//flag that keeps employee ids
  for(Iterator it=list.listIterator();it.hasNext();){
   if(empIds.add(emp.getId())==false){//if found duplicate remove from the list
  for(Employee emp:list){


No comments:

Post a Comment