Thursday, 8 August 2013

remove duplicate values in a list java

if list contain duplicated object you want to remove them useing set. A Set is a Collection that cannot contain duplicate elements.
It models the mathematical set abstraction.Set adds the restriction that duplicate elements are prohibited. To Know More Visit Set Interface

Sample Code :-RemoveDuplicate.java

package com.javastoreroom.mytestapp;

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

public class RemoveDuplicate {

 public static void main(String[] args) {
  List list = new ArrayList();

  list.add("jan");
  list.add("feb");
  list.add("jan");
  list.add("march");
  list.add("April");
  list.add("jan");
  list.add("feb");
  list.add("may");
  list.add("may");

  System.out.println("======== List Details ==========================");
  for (String string : list) {
   System.out.print(string + ",");
  }

  // -- Use LinkedHashSet if you remain the order

  Set set2 = new LinkedHashSet();
  set2.addAll(list);
  list.clear();
  list.addAll(set2);

  System.out.println();
  System.out.println("======== LinkedHashSet Details =================");

  for (String string2 : list) {
   System.out.print(string2 + ",");
  }

  // -- HashSet does not retain the order

  Set set = new HashSet();
  set.addAll(list);
  list.clear();
  list.addAll(set);

  System.out.println();
  System.out.println("======== HashSet Details =======================");
  for (String string : list) {
   System.out.print(string + ",");
  }

 }

}


After executing output shown like this :-

Done :)