W3docs

How do I remove repeated elements from ArrayList?

To remove repeated elements from an ArrayList in Java, you can use the removeAll method and pass it a Collection containing the elements to be removed.

To remove repeated elements from an ArrayList in Java, you can create a new ArrayList initialized from a HashSet. This works because a HashSet automatically filters out duplicate values.

Here's an example:


import java.util.ArrayList;
import java.util.HashSet;

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

list = new ArrayList<>(new HashSet<>(list));

System.out.println(list); // [1, 2, 3] (order may vary)

In this example, we create an ArrayList containing the elements 1, 2, 3, 2, and 1. We then replace the list with a new ArrayList initialized from a HashSet. The HashSet is used because it only stores unique elements, effectively removing all duplicates. (Note: the original removeAll approach incorrectly removes any element found in the provided collection, which would clear the list entirely when the collection contains all elements.)

After the assignment, the ArrayList will contain only the unique elements 1, 2, and 3.

Note: This approach removes all duplicate elements from the ArrayList, not just consecutive duplicates. If you want to remove only consecutive duplicates, you can use a different approach, such as iterating through the ArrayList and using the remove method to remove duplicates as you encounter them.