如何从列表<Object>构建地图<Object, List<Object>>地图

How to build a Map<Object, List<Object>> map from a List<Object>

我构建了一个idMap如下:

class Item {
    private int id;
    private int skuId;
    //some getter and setter
}

Map<Integer, List<Integer>> buildIdMap(List<Item> items) {

    Map<Integer, List<Integer> idMap = Maps.newHashMap();

    for (Item item : items) {
        if (!idMap.contains(item.getId())) {
            idMap.put(item.getId(), List.newArrayList());
        }
        idMap.put(item.getId(), item.getSkuId());
    }
    return idMap;
}

如何利用 guava 或 java8 做同样的事情?

使用 Guava 的 Multimaps.index(Iterable<V>,Function<? super V,K>):

Multimap<Integer, Item> buildIdMap(List<Item> items) {
  return Multimaps.index(items, Item::getId);
}

我认为这与您的要求并不完全相同,但它会比您预期的方法更好地完成工作。

您可以这样使用 Java8,

Map<Integer, List<Integer>> idMap = items.stream()
        .collect(Collectors.groupingBy(Item::getId, 
                Collectors.mapping(Item::getSkuId, Collectors.toList())));