问题
I have an EnumSet and want to convert it to array of its ordinal values. For example:
enum MyEnum { A, B, C; }
EnumSet enumSet = EnumSet.of(MyEnum.A, MyEnum.C);
and what I want to get:
[0, 2]
回答1:
You should not use the raw type EnumSet without the <MyEnum>
part
EnumSet<MyEnum> enumSet = EnumSet.of(MyEnum.A, MyEnum.C);
A Java 8 solution:
MyEnum[] values = MyEnum.values();
int[] ordinals = IntStream.range(0, values.length).filter(i -> enumSet.contains(values[i])).toArray();
A pre-Java 8 solution:
int[] ordinals2 = new int[enumSet.size()];
int index = 0;
for (MyEnum e : enumSet)
ordinals2[index++] = e.ordinal();
Check that it worked:
System.out.println(Arrays.toString(ordinals));
System.out.println(Arrays.toString(ordinals2));
回答2:
You can do this with streams:
int[] ordinals = enumSet.stream().mapToInt(Enum::ordinal).toArray();
来源:https://stackoverflow.com/questions/32976896/convert-an-enumset-to-an-array-of-integers