Re: iterating the difference of two collections
"Daniel Pitts" <googlegroupie@coloraura.com> wrote in message
news:1168112344.436522.321840@v33g2000cwv.googlegroups.com...
Andreas Leitgeb wrote:
Given two Collection parameters a,b that I'm *not* supposed to modify,
what's the best way to iterate over the elements in a but not in b?
Create a new collection d with elements of a, then d.removeAll(b),
then iterate over d.
or
for(ElemType e:a) { if (b.contains(e)) continue; ... }
Actually it happens that Collection b is actually a Set,
so my preference would be for the second, except that it
feels hackish. Is this feeling right or wrong?
Either way works. If you have the answer, why ask the question?
If you wanted to get really tricky, you would create a custom
collections called "Difference" which defines a view into the
collection (a - b);
Or create a Subset class, constructed from a Set and an expression
determining which members of another Set are in the subset: (none of this
compiled or tested)
public class Subset extends AbstractSet implements Set {
public Subset(Set superset, Criterion criterion){ ... }
...
public interface Criterion {
public boolean isInSubset(Object member);
}
}
and implement a Difference criterion
public class Difference implements Subset.Criterion {
private Set toExclude;
public Difference(Set toExclude) {
this.toExclude = toExclude;
}
public boolean isInSubset(Object member) {
return !toExclude.contains(member);
}
}