您可能具有以下内容:
public Map<Integer, List<String>> getMap(List<String> strings) { return strings.stream().collect( Collectors.groupingBy(String::length, HashMap::new, Collectors.toCollection(ArrayList::new)) );}通过将收集器
groupingBy(classifier, mapFactory,downstream)传递给的所需地图的提供者,收集器可用于指定所需的地图类型
mapFactory。然后,用于收集分组到同一键的元素的下游收集器为
toCollection(collectionFactory),从而可以收集到从给定供应商获得的收集中。
这样可确保返回的映射为,
HashMap并且每个值中的列表均为
ArrayList。请注意,如果要返回map和collection的特定实现,则很可能希望该方法也返回这些特定类型,因此可以使用其属性。
如果您只想指定集合供应商并保留
groupingBy默认地图,则可以在上面的代码中省略供应商,并使用两个参数重载:
public Map<Integer, List<String>> getMap(List<String> strings) { return strings.stream().collect( Collectors.groupingBy(String::length, Collectors.toCollection(ArrayList::new)) );}附带说明一下,您可以为此使用通用方法:
public <K, V, C extends Collection<V>, M extends Map<K, C>> M getMap(List<V> list, Function<? super V, ? extends K> classifier, Supplier<M> mapSupplier, Supplier<C> collectionSupplier) { return list.stream().collect( Collectors.groupingBy(classifier, mapSupplier, Collectors.toCollection(collectionSupplier)) );}这一声明的好处是,你现在可以使用它具有特定
HashMap的
ArrayListS作为结果,或
linkedHashMap的
linkedListsS,如果主叫方希望它:
HashMap<Integer, ArrayList<String>> m = getMap(Arrays.asList("foo", "bar", "toto"), String::length, HashMap::new, ArrayList::new);linkedHashMap<Integer, linkedList<String>> m2 = getMap(Arrays.asList("foo", "bar", "toto"), String::length, linkedHashMap::new, linkedList::new);但是到那时,直接
groupingBy在代码中使用可能会更简单…



