bartektartanus bartektartanus - 4 months ago 13
Java Question

Remove every duplicated element from ArrayList

Please, before downvote - read the question and check the example - this is not duplicate!

I want to remove every duplicated element from ArrayList in Java, like this:

Original list: [4, 2, 2, 3, 4, 1]
Set result: [1, 2, 3, 4]
Desired result: [1, 3]


The obvious solution for duplicates - set does not work here.

My solution:

ArrayList<Integer> arrayList = new ArrayList<Integer>();
arrayList.add(5);
arrayList.add(1);
arrayList.add(5);
arrayList.add(1);
arrayList.add(5);
arrayList.add(2);
arrayList.add(3);

ArrayList<Integer> temp = new ArrayList<>(arrayList);

for(Integer number : new HashSet<Integer>(arrayList)){
temp.remove(number);
}

arrayList.removeAll(temp);


Any smarter/more clever solutions?

Answer

Alternatively you can check for frequency as remove as well. Collections.frequency(arrayList, number)

public static void main(String[] args) {
    ArrayList<Integer> arrayList = new ArrayList<Integer>();
    arrayList.add(5);
    arrayList.add(1);
    arrayList.add(5);
    arrayList.add(1);
    arrayList.add(5);
    arrayList.add(2);
    arrayList.add(3);

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

    for (Integer number : arrayList) {
        if (Collections.frequency(arrayList, number) == 1) {
            unique.add(number);
        }
    }

    System.out.println(unique);
}