Wednesday, September 14, 2011

Epic Interview Question: Remove all Duplicates from the array

Let the Array be [1,1,1,2,2,2,3,4,4,4,5]

Output should be [1,2,3,4,5]

Source Code:

package com.interview.epic;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class DuplicateRemoval {
    public static void main(String [] args)
   
    {
        Integer [] a = {1,1,1,2,2,3,4,4,5};
        List<Integer> intList = Arrays.asList(a);
        Set<Integer> set = new HashSet<Integer>(intList);
        System.out.println("set data");       
        for (Object temp: set)
        {
            System.out.println(temp);
        }
       
    }

}





1 comment:

  1. Convert the array to list and then convert the list to set.

    In this conversion set will automatically remove duplicates. we dont have to worry :)

    ReplyDelete