问题
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 or
Boolean
versus integers (obviously) - I want all members of the enum to be represented, with a
TRUE
for each enum element included in theEnumSet
and aFALSE
for each element that is excluded from theEnumSet
. The other Question’s array includes only the items found in theEnumSet
. (more importantly)
回答1:
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 ] );
}
}
回答2:
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);
回答3:
In Java 8 you could do it like this
List<Boolean> present = Arrays.stream(MyEnum.values()).map(enumSet::contains).collect(Collectors.toList());
To go the other way around you could do something like this
IntStream.range(0, present.size()).filter(present::get).mapToObj(i -> MyEnum.values()[i]).
collect(Collectors.toCollection(() -> EnumSet.noneOf(MyEnum.class)));
来源:https://stackoverflow.com/questions/38366382/convert-between-enumset-and-array-of-boolean-values