用于 Guava 不可变集合的 Java 8 收集器?

2022-01-22 00:00:00 java java-stream guava

我真的很喜欢 Java 8 流和 Guava 的不可变集合,但我不知道如何将两者结合使用.

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

例如,如何实现 Java 8 收集器,将流结果收集到 ImmutableMultimap?

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

加分:我希望能够提供键/值映射器,类似于 Collectors.toMap() 有效.

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

推荐答案

从21版开始,可以

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

相关文章