How do I erase repeating elements from the ArrayList?

Asked 2 years ago, Updated 2 years ago, 82 views

There is a string ArrayList, but I want to erase the repeated string from this list. What should I do?

list java collections arraylist duplicate

2022-09-21 23:08

1 Answers

We need to think about why we use a list that allows duplication. The easiest way to erase duplicate elements is to put them in Set. Set does not allow duplication. And put it back in the ArrayList.

List<String> al = new ArrayList<>();
// // add elements to al, including duplicates
Set<String> hs = new HashSet<>();
hs.addAll(al);
al.clear();
al.addAll(hs);

Like this. Of course, the order of ArrayList is mixed up.


2022-09-21 23:08

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.