A very common problem and I have used google collections and here is my code
public class FindByIdPredicate implements Predicate {
private Long entityId;
public FindByIdPredicate(final Long entityId) {
this.entityId = entityId;
}
@Override
public boolean apply(final IDObject input) {
return input.getId().equals(this.entityId);
}
/**
* Pass in the Collection
* @param Collection
* @return IdObject if present or null
*/
public IDObject getEntity(final Collection extends IDObject> collection) {
for (IDObject idObject : collection) {
if (this.apply(idObject)) {
return idObject;
}
}
return null;
}
/**
* @param Set
* @return IdObject if present or null
*/
@SuppressWarnings("unchecked")
public T getEntity(final Set extends IDObject> set) {
for (IDObject idObject : set) {
if (this.apply(idObject)) {
return (T) idObject;
}
}
return null;
}
}
Hope this helps