Convert an EnumSet to an array of integers

和自甴很熟 提交于 2019-12-24 11:51:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!