c12
c12

Reputation: 9827

Remove Duplicates from Two Dimensional ArrayList

I have a two dimensional ArrayList that I need to filter the duplicates out of.

current result of generateRows: [["one"], ["two"], ["three"], ["one"]]

Java Pseudo Code:

ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>();
rows = generateRows(); //method not shown, but returns a ArrayList<ArrayList<String>>
Set<String> set = new LinkedHashSet<String>();
for (ArrayList<String> list:rows) {
    set.addAll (list);
}
rows.clear();
rows.add(new ArrayList<String>(set));

current result after running above conversion code: [[one, two, three]]

desired result: [["one"], ["two"], ["three"]]

Upvotes: 1

Views: 2828

Answers (2)

aioobe
aioobe

Reputation: 421030

You can't store String values ("one", "two", "three") in a list which is supposed to store ArrayList<String> values.

To store the three strings, you'll need to create a new list of type ArrayList<String>.

ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>();
rows = generateRows();
Set<String> set = new LinkedHashSet<String>();
for (ArrayList<String> list:rows) {
    set.addAll (list);
}

//rows.clear();
//rows.add(new ArrayList<String>(set));

ArrayList<String> noDups = new ArrayList<String>(set);

Btw,

  • These lines...

    ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>();
    rows = generateRows();
    

    are equivalent to

    ArrayList<ArrayList<String>> rows = generateRows();
    

     

  • You should prefer to program against interfaces instead of concrete classes, so if I were you I would write it as

    List<List<String>> rows = generateRows();
    

Upvotes: 1

ring bearer
ring bearer

Reputation: 20783

Keeping code in same lines as what you have posted, here is what you have to do.

ArrayList<ArrayList<String>> rows = new ArrayList<ArrayList<String>>();
rows = generateRows(); //method not shown, but returns a ArrayList<ArrayList<String>>
Set<ArrayList<String>> set = new LinkedHashSet<ArrayList<String>>();
set.addAll(rows);
rows.clear();
rows.addAll(set);

Main issue with your routine:

Set<String> set = new LinkedHashSet<String>(); you are saying set is going to contain String types while your real set of objects to be unique is of ArrayList type

Upvotes: 2

Related Questions