Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Duplicates from ArrayList<ArrayList<String>> Object

Tags:

java

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]]
like image 442
c12 Avatar asked May 16 '26 05:05

c12


1 Answers

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);
}
like image 170
aioobe Avatar answered May 18 '26 17:05

aioobe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!