Tuesday, February 7, 2012

Removing duplicate elements from an Array


//Removing Duplicate elements from an Array
//Principle used: Use HashSet and store Array elements as List, Hashset will contain only unique elements.

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class DuplicateRemoval {
    public static void main(String[] args) {
        String strDuplicate[]={"1","2","3","4","3","2"};
        String[] str = new String[10];
        for(int i=0;i<10;i++){
            str[i] = "str";
        }
        Set s = new HashSet(Arrays.asList(str));
        System.out.println(s);
        
        Set sDup = new HashSet(Arrays.asList(strDuplicate)); //HashSet will only contain unique elements.
        System.out.println(sDup);
    }
}

//Output:
[str]          : Duplicates removed, we added 10 "str" but printed only 1.
[3, 2, 4, 1]   : Duplicates removed

1 comment: