I have an enum with 4 values, and I have a method signature that accepts an enum value. I would like to be able to do something with all enum values not passed as the argument to doSomething().
public void doSomething(EnumThing thing){
EnumThing[] thingValues = EnumThing.values();
List<EnumThing> valuesNotPassedAsArg = new ArrayList<EnumThing>();
for(EnumThing th : thingValues){
valuesNotPassedAsArg.add(th);
}
valuesNotPassAsArg.remove(thing);
//here I would loop through all valuesNotPassAsArg and do something with them
}
public enum EnumThing{
SOMETHING, SOMETHINGELSE, ANOTHERTHING;
}
Is there a cleaner way to do this? I feel as if the loop to get the items from the thingValues array is superfluous.
Look into EnumSet
. Specifically,
import java.util.EnumSet;
import static java.util.EnumSet.complementOf;
for (EnumThing t : complementOf(EnumSet.of(thing))) {
... do the work ...
}
Another way is to use Stream.of
method. For example:
public class EnumTest {
public static enum MyEnum {
VALUE1, VALUE2, VALUE3
}
public static void main(String[] args) {
Stream.of(MyEnum.values()).filter(v -> v != MyEnum.VALUE2).forEach(System.out::println);
}
}
Which prints:
VALUE1
VALUE3
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