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
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!
'Book > Effective Java' 카테고리의 다른 글
[Effective Java] Item 45: Use streams judiciously (0) | 2021.11.13 |
---|---|
[Effective Java] Item 43: Prefer method reference to lambda (0) | 2021.11.08 |
[Effective Java] Item 42: Prefer lambda to anonymous classes (0) | 2021.11.07 |
[Effective Java] Item 38: emulate extensible enums with interfaces (0) | 2021.11.06 |