Ulvi Bajarani
Ulvi Bajarani

Reputation: 13

Removing double Objects in Java List

For the exam, I train to write the some algorithms to the final exam. One of them is creating the reverse() method, which removes doubles in the List<> . The problem that the void method only removes one double or two. How can I change the method?

Here, the code of the List.java file. The methods removeFromBack(), removeFromFront(), insertAtBack(), insertAtFront(), print(), isEmpty(), the classes List and ListNode are already defined in Deitel's Java book. Additionally, all imports are done:

public void removeDuplicates() {
    ArrayList<T> toCheck = new ArrayList<T>();
    ListNode<T> current = firstNode;
    while (current != null) {
        toCheck.add(current.data);
        current = current.nextNode;
    }
    current = firstNode;
    HashSet<T> toCheck2 = new LinkedHashSet<T>();

    for (T element: toCheck) {
        toCheck2.add(element);
    }

    for (T element: toCheck2) {
        removeFromBack();
        insertAtBack(element);
    }
}

Upvotes: 0

Views: 391

Answers (3)

0xh3xa
0xh3xa

Reputation: 4859

you can add duplicates list and remove them like this:

    public void removeDuplicates() {
        ArrayList<T> elements = new ArrayList<T>();
        ListNode<T> current = firstNode;
        while (current != null) {
            if(!elements.contains(current.data))
              toCheck.add(current.data);
            else {
               // you have the duplicates, do your logic
            }
            current = current.nextNode;
        }
    }

Upvotes: 1

PatrickChen
PatrickChen

Reputation: 1420

For duplicates in List, you could always use Set to help to remove the duplicates:


public List<Integer> removeDuplicates(List<Integer> list) {
    Set<Integer> set = new HashSet<>(list); // remove all duplicates in set
    List<Integer> result = new ArrayList(set.size());
    for (Integer i : list) {
         if (set.contains(i)) {
             result.add(i);
             set.remove(i); // delete, so duplicate item will not be added to result twice
         }
    }

    return result;
}

Upvotes: 0

Fabian Zimbalev
Fabian Zimbalev

Reputation: 553

There are faster/more efficient ways depending on your needs but this one should basically always work:

public static <T> ArrayList<T> removeDuplicates(ArrayList<T> toCheck) {

    ArrayList<Integer> toRemove = new ArrayList<Integer>();

    for(int i = 0; i < toCheck.size(); i++) {
        T current = toCheck.get(i);

        for(int j = 0; j < toCheck.size(); j++) {
            if(j == i)continue;

            if(toCheck.get(j) == current) {
                toRemove.add(j);
            }
        }
    }

    Collections.sort(toRemove, Collections.reverseOrder());

    for(int i : toRemove) {
        toCheck.remove(i);
    }

    return toCheck;

}

Upvotes: 0

Related Questions