Reputation: 16080
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?
Upvotes: 2
Views: 1506
Reputation: 6507
There are many ways to do what you are looking to do. Here is one (where T is the type stored by your existing List):
Map<T, Integer>
. The integer will be used to store the number of times that item appears in your list.This approach will be fast even for large lists.
Upvotes: 3
Reputation: 8509
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);
}
Upvotes: 2
Reputation: 11051
You can use a loop to check for duplicates in an ArrayList, and then use remove()
on the ArrayList to remove the elements.
Please see the following:
{
ArrayList list;
// ...
while(true)
for(final Integer o : list) {
if(list.indexOf(o) != list.lastIndexOf(o)) {
while(list.remove(o));
continue;
}
break;
}
}
Alternatively a better approach would be to use a temporary Set
to store the objects to remove:
{
ArrayList list;
TreeSet<Integer> set = new TreeSet<>(); // Use your Set!
// ...
for(final Integer o : list)
if(list.indexOf(o) != list.lastIndexOf(o))
set.add(o);
for(final Integer o : set)
while(list.remove(o));
}
Upvotes: 1