Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ascertain input values to various functions in streams

This question my be a very primitive question with Java 8 collections.

How can I understand better how Java 8 passes input values between various stages within stream processing. If there is documentation explaining this clearly I am happy to read through, but I couldn't come across any.

For example, the groupingBy takes in a Function called classifier, this take in T type and transforms to K type.

static <T,K> Collector<T,?,Map<K,List<T>>> 
    groupingBy(Function<? super T,? extends K> classifier)

In the below example, we are passing on only type K. It is not clear when in streams the input values (Type T) will be automatically considered? How can I understand this better?

Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
.collect(groupingBy(BlogPost::getType));
like image 984
serah Avatar asked Dec 07 '25 04:12

serah


1 Answers

In the below example, we are passing on only type K. It is not clear when in streams the input values (Type T) will be automatically considered?

Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
            .collect(Collectors.groupingBy(BlogPost::getType));

Notice the method reference in the code, which is an equivalent to the functional interface Function<T,R> with the only method apply represented as getType() method from BlogPost in your code.

How can I understand this better?

One of the ways to understand the code better is to just rewrite the simplified code:

Function<? super BlogPost, ? extends BlogPostType> classifier = BlogPost::getType;
// ^^^__you can see the correlation with Collectors#groupingBy(classifier)

Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream()
            .collect(Collectors.groupingBy(classifier));

with a return type from the groupingBy being Collector<BlogPost, ?, Map<BlogPostType, List<BlogPOst>>> you can further collect the postPerType thanks to the Stream's collect implementaion which has the signature <R, A> R collect(Collector<? super T, A,R> collector).

like image 64
Naman Avatar answered Dec 08 '25 17:12

Naman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!