I have an EnumSet
and want to convert back-and-forth to/from an array of boolean primitives. If it works better, I could work with a List
instead of an array, and/or Boolean
objects rather than boolean primitives.
enum MyEnum { DOG, CAT, BIRD; }
EnumSet enumSet = EnumSet.of( MyEnum.DOG, MyEnum.CAT );
What I want to get on the other end is an array that looks like this:
[TRUE, TRUE, FALSE]
This Question here is similar to this one, Convert an EnumSet to an array of integers. Differences:
Boolean
versus integers (obviously)TRUE
for each enum element included in the EnumSet
and a FALSE
for each element that is excluded from the EnumSet
. The other Question’s array includes only the items found in the EnumSet
. (more importantly)To convert an enum to an array of objects: Use the Object. keys() method to get an array of the enum's keys. Filter out the unnecessary values for numeric enums.
boolean[] isPrime = new boolean[10]; Arrays. fill(isPrime, true); This will assign all the elements of the array with true. Because by default the boolean array has all elements as false.
An array of booleans are initialized to false and arrays of reference types are initialized to null. In some cases, we need to initialize all values of the boolean array with true or false. We can use the Arrays.
A boolean array is a numpy array with boolean (True/False) values. Such array can be obtained by applying a logical operator to another numpy array: import numpy as np a = np.
To do that you'd basically write
MyEnum[] values = MyEnum.values(); // or MyEnum.class.getEnumConstants()
boolean[] present = new boolean[values.length];
for (int i = 0; i < values.length; i++) {
present[i] = enumSet.contains(values[i]);
}
Going the other direction, from boolean array present
created above to enumSet_
created below.
EnumSet<MyEnum> enumSet_ = EnumSet.noneOf ( MyEnum.class ); // Instantiate an empty EnumSet.
MyEnum[] values_ = MyEnum.values ();
for ( int i = 0 ; i < values_.length ; i ++ ) {
if ( present[ i ] ) { // If the array element is TRUE, add the matching MyEnum item to the EnumSet. If FALSE, do nothing, effectively omitting the matching MyEnum item from the EnumSet.
enumSet_.add ( values_[ i ] );
}
}
For the present, I don't see a better solution than
Boolean[] b = Arrays.stream(MyEnum.values()).map(set::contains).toArray(Boolean[]::new);
To get an EnumSet
from an array of boolean
primitives by using zip
MyEnum[] enums = zip(Arrays.stream(MyEnum.values()), Arrays.stream(b),
(e, b) -> b ? e : null).filter(Objects::nonNull).toArray(MyEnum[]::new);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With