I am performing some maintenance tasks on an old system. I have an arraylist that contains following values:
a,b,12
c,d,3
b,a,12
d,e,3
a,b,12
I used following code to remove duplicate values from arraylist
ArrayList<String> arList;
public static void removeDuplicate(ArrayList arlList)
{
HashSet h = new HashSet(arlList);
arlList.clear();
arlList.addAll(h);
}
It works fine, if it finds same duplicate values. However, if you see my data carefully, there are some duplicate entries but not in same order. For example, a,b,12 and b,a,12 are same but in different order.
How to remove this kind of duplicate entries from arraylist?
Thanks
Try this simple solution...(No Set interface used)
https://stackoverflow.com/a/19434592/369035
Wrap the element as "
Foo
" instead of "String
", rest of code 'removeDuplicate
' remains:Then
arList
will beArrayList < Foo>
.Assuming the entries are String. Then you can sort each of the entry and then do the duplicate check. Then you can store the entry in a map and use the contains(key) to see if they exist.
EDIT: added a complete code example.
Prints:
a,b,12
c,d,3
d,e,3
Create a class to wrap around a row string (triplet) to provide your equality semantics. Implement the equals() and hashCode() methods. Then use the HashSet method to remove duplicates.
In
ArrayList
we don't have a chance to remove duplicate elements directly. We can achieve it with sets, because sets don't allow duplicates, so, better to useHashSet
orLinkedHashSet
classes. See reference.