栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何转换清单 进入地图>,使用Java 8流和自定义List和Map供应商?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何转换清单 进入地图>,使用Java 8流和自定义List和Map供应商?

您可能具有以下内容:

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
ArrayList
S作为结果,或
linkedHashMap
linkedLists
S,如果主叫方希望它:

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
在代码中使用可能会更简单…



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/437675.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号