You want to use the Set retainAll method to get the intersection of two sets:
public class Test {
public enum Kind { CLASS, FIELD, METHOD }
public void applyMask(char kind, EnumSet<Kind> flags) {
final EnumSet<Kind> mask;
switch (kind) {
case 'C': mask = EnumSet.of(Kind.CLASS); break;
case 'F': mask = EnumSet.of(Kind.FIELD); break;
case 'M': mask = EnumSet.of(Kind.METHOD); break;
default: mask = EnumSet.allOf(Kind.class); break;
}
EnumSet<Kind> badFlags = EnumSet.copyOf(flags);
badFlags.removeAll(mask);
flags.retainAll(mask);
}
}
Note. I used to have the following line instead of a simpler one removeAll. Tom Hotin noted that it is removeAlleasier and achieves the same goal. Initially, I just copied the original OP logic as close as possible without trying to optimize.
badFlags.retainAll(EnumSet.complementOf(mask));