A Rec
object has a member variable called tag
which is a String
.
If I have a List
of Rec
s, how could I de-dupe the list based on the tag
member variable?
I just need to make sure that the List
contains only one Rec
with each tag
value.
Something like the following, but I'm not sure what's the best algorithm to keep track counts, etc:
private List<Rec> deDupe(List<Rec> recs) {
for(Rec rec : recs) {
// How to check whether rec.tag exists in another Rec in this List
// and delete any duplicates from the List before returning it to
// the calling method?
}
return recs;
}
Store it temporarily in a HashMap<String,Rec>
.
Create a HashMap<String,Rec>
. Loop through all of your Rec
objects. For each one, if the tag
already exists as a key in the HashMap
, then compare the two and decide which one to keep. If not, then put it in.
When you're done, the HashMap.values()
method will give you all of your unique Rec
objects.