Loop through a subset of an enum values
@Marko's answer is better than this, but it might be helpful to know of this alternative way.
public static void main(String[] args) {
EnumThing thing = EnumThing.ANOTHERTHING;
List<EnumThing> list = new ArrayList<EnumThing>(Arrays.asList(EnumThing.values()));
list.remove(thing);
System.out.println(list);
}
public enum EnumThing{
SOMETHING, SOMETHINGELSE, ANOTHERTHING;
}
This prints out
[SOMETHING, SOMETHINGELSE]
Looking at your title, to iterate a range you do
for (int i = YourEnum.___RANGE___START___.ordinal() +1; i != YourEnum.__RANGE___END___.ordinal() ; i++) {
YourEnumvalue = YourEnum.values()[i];
//use value
}
or this
for (YourEnum value: EnumSet.range(YourEnum.___RANGE___START___, YourEnum.__RANGE___END___)) {
// use value
}
I you just want to skip a single element, then Skip Head's solution might outperform the complementOf, which seems to be an overkill in case of single iteration.
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