Is there any way to elegantly initialize and populate a multi-value Map
using Java 8\'s stream API?
I know it\'s possible to cr
If you use forEach
, it’s much simpler to use computeIfAbsent
instead of compute
:
Map> personsByName = new HashMap<>();
persons.forEach(person ->
personsByName.computeIfAbsent(person.getName(), key -> new HashSet<>()).add(person));
However, when using the Stream API, it’s preferable to use collect
. In this case, use groupingBy
instead of toMap
:
Map> personsByName =
persons.collect(Collectors.groupingBy(Person::getName, Collectors.toSet());