Remove duplicate elements in an ArrayList without using HashSet
Asked Answered
D

9

6

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));
    }
}
Duffey answered 2/10, 2012 at 19:46 Comment(6)
Then you can create a new list and add items to it.. skipping duplicates..Estragon
Just out of curiosity or is use of HashSet prohibited by the teacher? :)Lenette
how is for (int dupWord : wordDulicate) { compiling?Zareba
dupWord should be a String not an intRumph
Nope, I just prohibited the easy way. Wanted to learn the tough way :) So, I can love HashSet even more.Duffey
You compare one entry of the list with the whole list if(wordDulicate.equals(dupWord))...Bulldog
I
6

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]
Infatuate answered 2/10, 2012 at 19:50 Comment(7)
Why are you removing from original list?Cairistiona
I thought that was requirement, if NOT, we can do just ! (NOT) check.Infatuate
I'm new to Iterator. Can I ask why you used to Iterator?Duffey
Iterator allows you to loop through the collection. docs.oracle.com/javase/1.5.0/docs/api/java/util/Iterator.htmlInfatuate
So, is that the best way to loop through a collection?Duffey
Take a look at the for-each-loop, too. It makes use of the Iterator interface and reads much easier.Bulldog
This is throwing ConcurrentModificationExceptionVicky
E
9

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);
    }
}
Estragon answered 2/10, 2012 at 19:49 Comment(0)
D
6

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

Despoil answered 2/10, 2012 at 19:49 Comment(0)
I
6

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]
Infatuate answered 2/10, 2012 at 19:50 Comment(7)
Why are you removing from original list?Cairistiona
I thought that was requirement, if NOT, we can do just ! (NOT) check.Infatuate
I'm new to Iterator. Can I ask why you used to Iterator?Duffey
Iterator allows you to loop through the collection. docs.oracle.com/javase/1.5.0/docs/api/java/util/Iterator.htmlInfatuate
So, is that the best way to loop through a collection?Duffey
Take a look at the for-each-loop, too. It makes use of the Iterator interface and reads much easier.Bulldog
This is throwing ConcurrentModificationExceptionVicky
M
3

Seems little late to the party, but with single arraylist,

Here's the code without hashset...

strings = new ArrayList<>();
    strings.add("a1");
    strings.add("a2");
    strings.add("ss");
    strings.add("asd");
    strings.add("asd");
    strings.add("a1");
    strings.add("ss");
    strings.add("ss");
    System.out.println(Collections.frequency(strings, "ss"));
    for(int i = 0; i< strings.size();i++){
        int frequency = Collections.frequency(strings, strings.get(i));
        if(frequency>1){
            String string = strings.get(i);
            for(int j = 1 ; j < frequency ; j++)
                strings.remove(string);
        }
    }
    System.out.println(Collections.frequency(strings, "ss"));
    System.out.println(strings);
Modernism answered 5/3, 2015 at 4:28 Comment(0)
H
2
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ArrayListDuplicateRemove {

    public static void main(String[] args) {


       List<String> lst = new LinkedList<String>();
        lst.add("ABC");
        lst.add("ABC");
        lst.add("ABCD");
        lst.add("ABCD");
        lst.add("ABCE");

        System.out.println("Duplicates List "+lst);

        Object[] st = lst.toArray();
          for (Object s : st) {
            if (lst.indexOf(s) != lst.lastIndexOf(s)) {
                lst.remove(lst.lastIndexOf(s));
             }
          }

        System.out.println("Distinct List "+lst);

    }

}
Hemorrhage answered 27/3, 2015 at 9:17 Comment(1)
You should explain what your code is doing, and how it answers the OP's question.Perlman
R
1
package arraylist;

import java.util.ArrayList;
import java.util.Iterator;

class Student{
    String name;
    String dob;
    public Student(String name, String dob) {
        super();
        this.name = name;
        this.dob = dob;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDob() {
        return dob;
    }
    public void setDob(String dob) {
        this.dob = dob;
    }

    public String toString() {
        return name+"\t"+dob;
    }
}

public class RemoveDuplicate {

    public static void main(String[] args) {

        ArrayList<Student> list=new ArrayList<Student>();
        list.add(new Student("prakash", "89"));
        list.add(new Student("prakash", "89"));
        list.add(new Student("saurabh", "79"));
        list.add(new Student("saurabh", "79"));

        Iterator<Student> it=list.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
        }

        int size=list.size();
        for(int i=0;i<size-1;i++){
            for(int j=i+1;j<size-1;j++){
                if(list.get(i).getName().equals(list.get(j).getName())){
                    list.remove(j);
                }
            }
        }
            System.out.println(list);
    }
}
Recrudesce answered 15/8, 2015 at 8:47 Comment(0)
P
0
 ArrayList l1 = new ArrayList();
ArrayList l2 = new ArrayList();

Iterator iterator = l1.iterator();

    while (iterator.hasNext())
    {
        YourClass o = (YourClass) iterador.next();
        if(!l2.contains(o)) l2.add(o);
    }

l1 is the original list, and l2 is the list whithout repeated items (Make sure YourClass has the equals method acording to what you want to stand for equality)

Ptyalism answered 2/10, 2012 at 19:51 Comment(0)
H
0
ArrayList<Integer> al = new ArrayList<Integer>();

Scanner sc = new Scanner(System.in);
for(int i=0;true;i++){
    System.out.println("Enter your Element:");
     String s1= sc.nextLine();
     if(s1.equals("Exit")){
         break;
     }
     int x1= Integer.parseInt(s1);
     al.add(x1);

     for(int j=0;j<al.size();j++){
         for(int k=j+1;k<al.size();k++){

             int temp;
             if(al.get(j).intValue()>al.get(k).intValue()){
                 temp =al.get(j).intValue();
                 al.set(j, al.get(k).intValue());
                 al.set(k, temp);

             }//if
         }//for
     }//for
}//for
System.out.println(al);
Habsburg answered 9/9, 2015 at 16:42 Comment(1)
Here we can add one by one integer element from console to our java class by using scanner class object and after that we can check for the element sortingHabsburg
D
-1
public static void main(String[]args){
       ArrayList<String> al = new ArrayList<String>();
       al.add("Tom");
       al.add("jerry");
       al.add("mike");
       al.add("jerry");
      ArrayList<String> names = new ArrayList<String>();
       for(String dupli : al){
           if(!names.contains(dupli)){
               names.add(dupli);
           }
       }
       System.out.println(names);
    }
Delores answered 18/2, 2024 at 14:14 Comment(2)
It's great you're trying to contribute, but this is really a bad answer. First it is a code only answer, you haven't explained at all why this is an answer. Second the question explicitly says: "Without using a HashSet" your edit fixed that I suppose. Third, what does this offer that is different than the previous answers?Electrophilic
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Signory

© 2022 - 2025 — McMap. All rights reserved.