Java 8 collector for Guava immutable collections?

前端 未结 5 2235
花落未央
花落未央 2020-12-17 09:55

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 Collec

5条回答
  •  别那么骄傲
    2020-12-17 10:16

    For your example, you can use Guava's toImmutableMap() collector. E.g.

    import static com.google.common.collect.ImmutableMap.toImmutableMap;
    
    ImmutableMap zipCodeForName =
        people.stream()
            .collect(
                toImmutableMap(Person::getName, p -> p.getAddress().getZipCode()));
    
    ImmutableMap personForName =
        people.stream()
            .collect(
                toImmutableMap(Person::getName, p -> p));
    

    The top answer has the rest of the Guava immutable collectors APIs

提交回复
热议问题