Search code examples
javaandroidarraysenumsenumset

Convert an EnumSet to an array of integers


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]

Solution

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