解释 Java 8 收藏家 Interface/Method 签名
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
如何 return Map<String, List<Student>>
给定上面的签名。有人可以解释一下如何阅读这个签名吗?
假设以下最小值 class:
class Student {
String teachersName;
public String getTeachersName() {
return teachersName;
}
}
您可以通过在每一步输入和输出匹配 return 类型来关联您的代码。例如,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();
}
})
你的情况 returns
Collector<Student, ?, Map<String, List<Student>>>
此外,如果您查看 collect
操作的签名,即
// <R, A> R collect(Collector<? super T, A, R> collector)
因此在您的情况下 returning R
如 :
Map<String, List<Student>>
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
如何 return Map<String, List<Student>>
给定上面的签名。有人可以解释一下如何阅读这个签名吗?
假设以下最小值 class:
class Student {
String teachersName;
public String getTeachersName() {
return teachersName;
}
}
您可以通过在每一步输入和输出匹配 return 类型来关联您的代码。例如,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();
}
})
你的情况 returns
Collector<Student, ?, Map<String, List<Student>>>
此外,如果您查看 collect
操作的签名,即
// <R, A> R collect(Collector<? super T, A, R> collector)
因此在您的情况下 returning R
如 :
Map<String, List<Student>>