这很容易转化List<V>
成Map<K, List<V>>
。例如:
public Map<Integer, List<String>> getMap(List<String> strings) {
return
strings.stream()
.collect(Collectors.groupingBy(String::length));
}
但我想用我自己做List
和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));
而如果我只需要定义的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
。请注意,如果你想返回地图和收集的具体实现,那么你很可能希望该方法返回的特定类型为好,这样就可以使用它们的属性。
如果你只需要指定一个集合的供应商,并保持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
的代码...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句