Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through a subset of an enum values

Tags:

java

enums

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.

like image 1000
andersra Avatar asked Jan 08 '13 21:01

andersra


2 Answers

Look into EnumSet. Specifically,

import java.util.EnumSet;
import static java.util.EnumSet.complementOf;

for (EnumThing t : complementOf(EnumSet.of(thing))) {
  ... do the work ...
}
like image 176
Marko Topolnik Avatar answered Sep 28 '22 20:09

Marko Topolnik


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
like image 34
George Z. Avatar answered Sep 28 '22 21:09

George Z.