Help me choose
Book/Effective Java

[Effective Java] Item 37: Using EnumMap as a way to group items by enum

by hajinny 2021. 11. 5.

Why should you read this article?

- You want to group collection into different groups, by enum.

- You want to avoid using Set[] and use Map, but want to minimise memory consumption (ie not use HashMap, but something equivalent in memory consumption to simple array that is fixed sized)

 

Let's get started!

 

Oftentimes, a list (or any kind of collection) might need to be grouped into separate groups. For example, suppose that we have a list of students, and we want to group them by year levels. Suppose that the year level field of a student is represented by enum, like the following:

 

Student class

Expect constructor, getters and setters to complete this class' definition

 

Further, suppose we have a List<Student> students that is to be grouped by year levels.

A naive approach to grouping students is to just use standard stream and collect:

This is fine for basic usecases.

 

However, the implementation of Map generated is a HashMap by default, meaning that it will be much more space-consuming than simple Set[].

EnumMap implementation has much less space complexity, because it initializes keyset with the predefined set of enums. So it doesn't necessarily create multiple buckets (like HashMap does).

 

Hope this article has been helpful, and see you again. Later!