Idiomatically creating a multi-value Map from a Stream in Java 8

前端 未结 1 2043
庸人自扰
庸人自扰 2021-02-08 03:58

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

1条回答
  •  情书的邮戳
    2021-02-08 04:05

    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());
    

    0 讨论(0)
提交回复
热议问题