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.
Try this:
private List<Rec> deDupe(List<Rec> recs) {
Set<String> tags = new HashSet<String>();
List<Rec> result = new ArrayList<Rec>();
for(Rec rec : recs) {
if(!tags.contains(rec.tags) {
result.add(rec);
tags.add(rec.tag);
}
}
return result;
}
This checks each Rec
against a Set
of tags. If the set contains the tag already, it is a duplicate and we skip it. Otherwise we add the Rec
to our result and add the tag to the set.
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