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.
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.removeAll(new HashSet<>(list));
System.out.println(list); // [2, 3]
In this example, we create an ArrayList containing the elements 1
, 2
, 3
, 2
, and 1
. We then use the removeAll
method and pass it a HashSet
containing the ArrayList to remove all duplicate elements. The HashSet
is used to remove duplicates because it does not allow duplicate elements.
After the removeAll
method is called, the ArrayList will contain only the unique elements 2
and 3
.
Note: This method will remove 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.