If you'd like to have a reusable toEnumSet()
collector:
<E extends Enum<E>> Collector<E, ?, EnumSet<E>> toEnumSet() {
return Collectors.collectingAndThen(Collectors.toSet(), EnumSet::copyOf);
}
EnumSet<Amenities> fromBitFlags(int bitFlag) {
return ALL_OPTS.stream()
.filter(a -> (a.ameityId & bitFlag) > 0)
.collect(toEnumSet()));
}
If you don't need to reuse it, you can of course in-line it:
EnumSet<Amenities> fromBitFlags(int bitFlag) {
return ALL_OPTS.stream()
.filter(a -> (a.ameityId & bitFlag) > 0)
.collect(collectingAndThen(toSet(), EnumSet::copyOf));
}
(assuming static imports from Collectors
)
Alternatively, you can just wrap your original Set<Amenities>
result:
EnumSet<Amenities> fromBitFlags(int bitFlag) {
return EnumSet.copyOf(
ALL_OPTS.stream()
.filter(a -> (a.ameityId & bitFlag) > 0)
.collect(toSet()));
}
Just for fun of it — you can also use reduce:
.reduce(EnumSet.noneOf(Amenities.class), // identity
EnumSet::add, // accumulator
EnumSet::addAll)); // combiner
but that's hard to reuse, so maybe better a reducing collector:
.collect(reducing(
EnumSet.noneOf(Amenities.class), // identity
EnumSet::of, // mapper
EnumSet::addAll)); // combiner
() -> EnumSet.noneOf(Amenities.class)
, how this creates a Supplier that can automatically callEnumSet.add()
– Ladin