I have 2 lists with same Object type.
List A [ foo, bar, moo, woo, pee ]
List B [ bar, woo ]
I want to compare those 2 lists and if the name matches, set its property to true.
For instance,
if(ListA[1].name.equals(ListB[0].name)) { //match name 'bar' and 'bar'
ListA[1].hasSameName = true;
}
something like that.
I can write O(N^2) solution.
for(Talent checkedTalent : ListA) {
for(Talent filteredTalent : ListB) {
if( checkedTalent.Id.equals(filteredTalent.Id) ) {
filteredTalent.isSelected = true;
}
}
}
Can this be done in more efficient way?
Use hashing for an O(n) solution (assuming an efficient hash implementation):
Set<String> ids = new HashSet<String>(ListA.size());
for(Talent checkedTalent : ListA) {
ids.add(checkedTalent.Id);
}
for(Talent filteredTalent : ListB) {
if (ids.contains(filteredTalent.Id)) {
filteredTalent.isSelected = true;
}
}
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