Convert an EnumSet to an array of integers

2019-08-12 16:32发布

问题:

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