In the last blog post we discovered EnumMaps for mappings with enum keys. You might have observed that there is also a specialized Set that is optimized for enums: EnumSet.
We again define a CoffeeType enum:
public enum CoffeeType {
ESPRESSO, POUR_OVER, FRENCH_PRESS, LATTE, FLAT_WHITE
}Now we can create sets of this enum type, by using the EnumSet implementation:
Set<CoffeeType> favoriteCoffeeTypes = EnumSet.of(ESPRESSO, POUR_OVER, LATTE); assertThat(favoriteCoffeeTypes).containsOnly(ESPRESSO, POUR_OVER, LATTE);
The favoriteCoffeeTypes still acts like any Set, that is, adding duplicates wonβt change its contents:
favoriteCoffeeTypes.add(POUR_OVER); assertThat(favoriteCoffeeTypes).containsOnly(ESPRESSO, POUR_OVER, LATTE);
Interesting side note: If you look into the JDK, youβll see that EnumSet is implemented by both RegularEnumSet and JumboEnumSet; the number of enum elements determines the implementation being used. If youβre interested in how the EnumSet implementation manage to be highly efficient, I challenge you to have a look into these classes. Hint: Bitwise operations :-)
This post was reposted from my newsletter issue 018.
| Published on Java Code Geeks with permission by Sebastian Daschner, partner at our JCG program. See the original article here: EnumSet for enum collections Opinions expressed by Java Code Geeks contributors are their own. |
Thank you!
We will contact you soon.
Sebastian DaschnerJanuary 22nd, 2018Last Updated: January 23rd, 2018

This site uses Akismet to reduce spam. Learn how your comment data is processed.