[英]Encapsulating Collection to Map transformation using Java 8's streams and collectors into a method
I believe this question is not a duplicate despite the numerous questions about converting lists to maps in Java 8. Please bear with me. 我相信这个问题并不重复,尽管有很多关于在Java 8中将列表转换为地图的问题。请耐心等待。
What I'm trying to do is gradually building a library of functions for myself to avoid having to repeat convoluted coded over and over involving streams and collectors, which tend to be much too verbose. 我正在尝试做的是逐步为自己构建一个函数库,以避免不得不重复复杂的编码一遍又一遍地涉及流和收集器,这往往过于冗长。
At the moment I'm stuck in creating a method that transforms a collection into a map grouping by some field of the object of the collection. 目前,我一直在创建一个方法,该方法将集合转换为集合对象的某个字段的地图分组。
Let's say we have this class: 假设我们有这个课程:
class SomeClass {
private String someField;
private String anotherfield;
public String getSomeField() {
return someField;
}
public String getAnotherField() {
return anotherfield;
}
}
And a list: 还有一个清单:
List<SomeClass> myList = new ArrayList<SomeClass>();
//populate the list...
And we want this, where each key of the map is a unique value for someField
in the objects of the list: 我们想要这个,其中地图的每个键都是列表对象中
someField
的唯一值:
Map<String,List<SomeClass>> myMap;
Which can be done like this: 可以这样做:
Map<String,List<SomeClass>> myMap =
myList.stream().collect(Collectors.groupingBy(o -> o.getSomeField() ));
Here's the part that I can't solve. 这是我无法解决的部分。 As I said I want to hide this into a cleaner method in a utility class that I intend to use in my projects.
正如我所说,我想把它隐藏在我打算在我的项目中使用的实用程序类中的一个更干净的方法中。 The method's signature:
方法的签名:
public static <T, R> Map<R, List<T>> collectionToMap(
Collection<T> coll, Function<? super T, ? extends R> groupByKey)
Which would be called like: 这将被称为:
Map<String,List<SomeClass>> amap = collectionToMap(myList, o -> o.getSomeField());
Here is a clumsy attempt that doesn't compile, but just to give you an idea: 这是一个笨拙的尝试,不能编译,但只是为了给你一个想法:
public static <T, R> Map<R, List<T>> collectionToMap(Collection<T> coll, Function<? super T, ? extends R> groupByKey) {
Map<R,List<T>> amap = coll.stream().collect(Collectors.groupingBy(
T::groupBy,
Collectors.mapping(T, Collectors.toList())
));
return amap;
}
I can't wrap my head around it. 我无法绕过它。
You don't need mapping
. 您不需要
mapping
。 You just have to pass the groupByKey
Function
to groupingBy
: 您只需将
groupByKey
Function
传递给groupingBy
:
public static <T, R> Map<R, List<T>> collectionToMap(Collection<T> coll, Function<? super T, ? extends R> groupByKey) {
return coll.stream().collect(Collectors.groupingBy(groupByKey));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.