大佬教程收集整理的这篇文章主要介绍了如何转换清单 进入地图>,使用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)
传递给的所需地图的提供者,收集器可用于指定所需的地图类型@H_141_5@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
在代码中使用可能会更简单…
轻松转换List<V>
成@H_141_5@map<K,List<V>>。例如:
public Map<Integer,List<String>> getMap(List<String> Strings) {
return
Strings.stream()
.collect(Collectors.groupingBy(String::length));
}
但是我想和我自己List
以及@H_141_5@map 供应商 一起做。
我想出了这个:
public Map<Integer,List<String>> getMap(List<String> Strings) {
return Strings.stream()
.collect(Collectors.toMap(
String::length,item -> {List<String> list = new ArrayList<>(); list.add(item); return list;},(list1,list2) -> {list1.addAll(list2); return list1;},HashMap::new));
}
问题: 是否有一种更简单,更省时或更有效的方法?例如,像这样的东西(不起作用):
return Strings.stream()
.collect(Collectors.toMap(
String::length,ArrayList::new,HashMap::new));
以上是大佬教程为你收集整理的如何转换清单 进入地图>,使用Java 8流和自定义List和Map供应商?全部内容,希望文章能够帮你解决如何转换清单 进入地图>,使用Java 8流和自定义List和Map供应商?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。