java stream groupingBy with EnumMap or other?

Which version should I prefer in terms of fastest and lowest memory?

version 1:

public Map<TYPE, List<Task>> getTaskByType() {
    return tasks.stream()
            .collect(Collectors.groupingBy(Task::getType, 
                     () -> new EnumMap<>(TYPE.class), 
                     Collectors.toList()));
    }

version 2:

public Map<TYPE, List<Task>> getTaskByType() {
    return tasks.stream().collect(Collectors.groupingBy(Task::getType));
}

or another version?

Edit:

If you have a lots of Enums then use version 1!

1
Leave a Reply

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
Jason Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
Jason
Guest

Your second snippet produces a HashMap (although that’s a non-guaranteed implementation detail).

So your question is answered by the javadoc of EnumMap:

This representation is extremely compact and efficient. […] All basic operations execute in constant time. They are likely (though not guaranteed) to be faster than their HashMap counterparts.

But I agree with every other commenter: the chance of this having any significant impact on the performance or memory consumption of your app is very low, and you should favor readability rather than micro-optimizations than decrease it.