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
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.
© 2024 OneMinuteCode. All rights reserved.