Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicate elements in an ArrayList without using HashSet

My logic is messed up. I am just trying to work out a way to remove duplicates in an ArrayList without using a HashSet.

public static void main(String[] args) {
    ArrayList<String> wordDulicate = new ArrayList<String>();
    wordDulicate.add("Tom");
    wordDulicate.add("Jones");
    wordDulicate.add("Sam");
    wordDulicate.add("Jamie");
    wordDulicate.add("Robie");
    wordDulicate.add("Helen");
    wordDulicate.add("Tom");
    wordDulicate.add("Troy");
    wordDulicate.add("Mika");
    wordDulicate.add("Tom");

    for (String dupWord : wordDulicate) {
        if (wordDulicate.equals(dupWord))
            System.out.println(wordDulicate.get(dupWord));
    }
}
like image 973
AppSensei Avatar asked Oct 02 '12 19:10

AppSensei


3 Answers

You can create another list, and add items to it, skipping the duplicates: -

ArrayList<String> wordDulicate = new ArrayList<String>();
ArrayList<String> tempList= new ArrayList<String>();

wordDulicate.add("Tom");
wordDulicate.add("Jones");
wordDulicate.add("Sam");


for (String dupWord : wordDulicate) {
    if (!tempList.contains(dupWord)) {
        tempList.add(dupWord);
    }
}
like image 83
Rohit Jain Avatar answered Oct 12 '22 23:10

Rohit Jain


This methodology requires having another list:

       ArrayList<String> wordDulicate = new ArrayList<String>();

        wordDulicate.add("Tom");
        wordDulicate.add("Jones");
        wordDulicate.add("Sam");
        wordDulicate.add("Jamie");
        wordDulicate.add("Robie");
        wordDulicate.add("Helen");
        wordDulicate.add("Tom");
        wordDulicate.add("Troy");
        wordDulicate.add("Mika");
        wordDulicate.add("Tom");

        ArrayList<String> nonDupList = new ArrayList<String>();

        Iterator<String> dupIter = wordDulicate.iterator();
        while(dupIter.hasNext())
        {
        String dupWord = dupIter.next();
        if(nonDupList.contains(dupWord))
        {
            dupIter.remove();
        }else
        {
            nonDupList.add(dupWord);
        }
        }
      System.out.println(nonDupList);

Output:

[Tom, Jones, Sam, Jamie, Robie, Helen, Troy, Mika]
like image 37
kosa Avatar answered Oct 12 '22 23:10

kosa


You should sort the list and remove the element that is equal to the previous one.

like image 34
dan Avatar answered Oct 12 '22 23:10

dan