[英]Explaining Java 8 Collector Interface/Method Signature
Stream.collect(Collector<? super T, A, R> collector)
<R,A> R collect(Collector<? super T,A,R> collector)
Performs a mutable reduction operation on the elements of this stream using a Collector.
Collectors.groupingBy(Function<? super T,? extends K> classifier)
public static <T,K> Collector<T,?,Map<K,List<T>>> groupingBy(Function<? super T,? extends K> classifier)
Returns a Collector implementing a "group by" operation on input elements of type T, grouping elements according to a classification function, and returning the results in a Map.
有人可以解释泛型T
, K
和R
吗? 我真的很困惑这种方法如何符合上面的签名:
List<Student> studentList = ....
Map<String, List<Student>> groupByTeachersMap = studentList.stream()
.collect(Collectors.groupingBy(Student::getTeachersName));
鉴于上面的签名,我看不到collect
如何返回Map<String, List<Student>>
。 有人可以解释如何阅读此签名吗?
假设以下最小类:
class Student {
String teachersName;
public String getTeachersName() {
return teachersName;
}
}
您可以通过在每个步骤中匹配输入和输出返回类型来关联您的代码。 例如, groupingBy
的签名为:
// <T, K> Collector<T, ?, Map<K, List<T>>> groupingBy(Function<? super T, ? extends K> classifier)
并且您的具体实现详述为:
Collectors.groupingBy(new Function<Student, String>() {
@Override
public String apply(Student student) {
return student.getTeachersName();
}
})
在你的情况下返回
Collector<Student, ?, Map<String, List<Student>>>
此外,如果您查看collect
操作的签名,即
// <R, A> R collect(Collector<? super T, A, R> collector)
因此,在您的情况下,返回R
如下:
Map<String, List<Student>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.