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();
  this.id = id;
  this.name = name;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.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();){
   Employee emp=it.next();
   if(empIds.add(emp.getId())==false){//if found duplicate remove from the list
    it.remove();
   }
  }
  
  for(Employee emp:list){
   System.out.println(emp.getId());
   System.out.println(emp.getName());
  }
  
 }

}

No comments:

Post a Comment