My code:
class BlogPost {
String title;
String author;
BlogPostType type;
int likes;
public BlogPost(String title, String author, BlogPostType type, int likes) {
this.title = title;
this.author = author;
this.type = type;
this.likes = likes;
}
//getter setter
}
and:
public enum BlogPostType {
NEWS,
REVIEW,
GUIDE
}
and:
public static void main(String[] args) {
List<BlogPost> posts = Arrays.asList(new BlogPost("Start Java", "Ram", BlogPostType.NEWS, 11),
new BlogPost("Start Java 8", "Rajou", BlogPostType.REVIEW, 101),
new BlogPost("Functional programming", "Das", BlogPostType.REVIEW, 111),
new BlogPost("Lambda", "Ramos", BlogPostType.GUIDE, 541));
Map<BlogPostType, List<BlogPost>> Blist = posts.stream().collect(groupingBy(BlogPost::getType));
System.out.println(Blist);
}}
I have three classes one is BlogPost
, BlogPostType
and Main
.
I am making a map of Map<BlogPostType, List<BlogPost>> Blist
by using groupingBy()
and it works perfectly fine. i used a method reference there BlogPost::getType , i can use lambda expression also (x) -> x.getType()
.
But when i try to change the type of Map , i.e Map<String, List<BlogPost>> Blist1
then i cannot use Method reference. Is there any possible way to use method reference and get the type also changed??
I am thinking why cant we use like this: BlogPost::getType.toString()
or (String)BlogPost::getType
while we can do this in lambda (x) -> x.getType().toString()
. Any possible ways to use Method reference and get along with conversion of type also?
you can use Function.identity()
to chain method references (as many as you want). For example, put the following function in groupingBy
:
Function.<BlogPost>identity()
.andThen(BlogPost::getType)
.andThen(BlogPostType::toString)
but it's better to use lambda