Search code examples
javaguavajava-stream

Java 8 collector for Guava immutable collections?


I really like Java 8 streams and Guava's immutable collections, but I can't figure out how to use the two together.

For example, how do I implement a Java 8 Collector that gathers stream results into an ImmutableMultimap?

Bonus points: I'd like to be able to provide key/value mappers, similar to how Collectors.toMap() works.


Solution

  • Since version 21, you can

    .collect(ImmutableSet.toImmutableSet())
    .collect(ImmutableMap.toImmutableMap())
    .collect(Maps.toImmutableEnumMap())
    .collect(Sets.toImmutableEnumSet())
    .collect(Tables.toTable())
    .collect(ImmutableList.toImmutableList())
    .collect(Multimaps.toMultimap(...))