使用 guava 将 collection 映射到 id

Use guava to map collection to id

我能做到:

Map<Long, MyBean> mappedbean = Maps.uniqueIndex(myBeanList, toId);

哪里

private final Function<BeanWithId, Long> toId=
            new Function<BeanWithId, Long>() {
                public Long apply(BeanWithId beanWithId) {
                    return beanWithId.getId();
                }
            };

但是我如何创建子列表映射,所以像这样:

Map<Long, List<MyBean>> mappedbean = Maps.somethingSomething(myBeanList, toId);

其中 id 不是 bean 上的 唯一 标识符。

一个无聊的旧 for 循环 ?

我不会为此使用 Guava,但是 Java 8 的 Stream API:

import static java.util.stream.Collectors.groupingBy;

final Map<Long, List<MyBean>> mappedbean = myBeanList.stream()
        .collect(groupingBy(MyBean::getId));

使用 Guava,您可以:

final Map<Long, Collection<MyBean>> mappedbean = Multimaps.index(myBeanList, toId).asMap();

尽管Multimaps.indexreturns一个ImmutableListMultimap,来自documentation for ListMultiMap

The returned map's values are guaranteed to be of type List. To obtain this map with the more specific generic type Map<K, List<V>>, call Multimaps.asMap(ListMultimap) instead.

所以转换为 Map<Long, List> 总是安全的,事实上你可以这样做:

final Map<Long, List<MyBean>> mappedbean = Multimaps.asMap(Multimaps.index(myBeanList, toId));

得到你想要的确切类型。 (感谢 的提示)