I have an ArrayList that has a nested ArrayList of Strings and I want to remove duplicates from. I know if I always wanted to remove duplicates, I shouldn't use an ArrayList, but in some cases duplicates are valid. What is the best way to remove duplicates from the nested ArrayList?
For example, I would like to execute some Java that converts:
[[duplicate], [duplicate], [duplicate], [unique1], [unique2]]
to:
[[duplicate], [unique1], [unique2]]
To remove duplicates from an ArrayList you could do
yourList = new ArrayList<String>(new LinkedHashSet<String>(yourList));
Using LinkedHashSet instead of a HashSet ensures that the order of the original lists are preserved.
Regarding your comment:
Here's a solution that transforms [[1,2,3], [1,2], [3], [1,2]] to [[1,2,3], [1,2], [3]].
Set<String> seen = new HashSet<String>();
for (List<String> l : strLists) {
for (Iterator<String> iter = l.iterator(); iter.hasNext(); )
if (!seen.add(iter.next()))
iter.remove();
// If you want to remove lists that end up empty:
if (l.isEmpty())
strLists.remove(l);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With