循环遍历枚举值的子集

时间:2013-01-08 21:08:45

标签: java enums

我有一个包含4个值的枚举,我有一个接受枚举值的方法签名。我希望能够对所有未作为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;
}

有更清洁的方法吗?我觉得好像从thingValues数组中获取项目的循环是多余的。

6 个答案:

答案 0 :(得分:21)

查看EnumSet。具体地,

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

for (EnumThing t : complementOf(EnumSet.of(thing))) {
  ... do the work ...
}

答案 1 :(得分:3)

@Marko的回答比这更好,但知道这种替代方式可能会有所帮助。

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;
}

打印出来

  

[SOMETHING,SOMETHINGELSE]

答案 2 :(得分:1)

查看标题,迭代范围即可

for (int i = YourEnum.___RANGE___START___.ordinal() +1; i != YourEnum.__RANGE___END___.ordinal() ; i++) {
    YourEnumvalue = YourEnum.values()[i];
    //use value
}

或者

for (YourEnum value: EnumSet.range(YourEnum.___RANGE___START___, YourEnum.__RANGE___END___)) {
    // use value
}

我只想跳过一个元素,然后Skip Head's solution可能胜过complementOf,这在单次迭代的情况下似乎有点过分。

答案 3 :(得分:0)

public void doSomething(EnumThing thing){
   EnumThing[] thingValues = EnumThing.values();
   for(EnumThing th : thingValues){
       if (th != thing) {
          doSomethingElse(th);
       }
   }
}

答案 4 :(得分:0)

这样的事情会更好一点我说

public void doSomething(EnumThing thing){
   EnumThing[] thingValues = EnumThing.values();
   List<EnumThing> valuesNotPassedAsArg = Arrays.asList(thingValues);
   valuesNotPassAsArg.remove(thing);
   //here I would loop through all valuesNotPassAsArg and do something with them
}
public enum EnumThing{
   SOMETHING, SOMETHINGELSE, ANOTHERTHING;
}

答案 5 :(得分:0)

另一种方法是使用Stream.of方法。例如:

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);
    }
}

哪些印刷品:

VALUE1
VALUE3