1

This code is straightforward :

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

where BlogPost is :

class BlogPost {
    String title;
    String author;
    String type;
    int likes;
    // getter setter
}

What if BlogPost has some other classes as fields and I want to group by one of those fields, e.g.

class BlogPost {
    String title;
    String author;
    Description description;
    int likes;
    // getter setter
}

class Description {
    String part1;
    String type;
    // getter setter
}

How can I access say

myBlogPost.getDescription().getType()

inside a lambda expression?

Pseudo code:

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

edit : groupingBy refers to :

import static java.util.stream.Collectors.groupingBy;
Wolf359
  • 2,620
  • 4
  • 42
  • 62

2 Answers2

3

Just create a lambda returning that expression:

groupingBy(p -> p.getDescription().getType())
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
2
Map<String, List<BlogPost>> postsPerType = posts.stream()
  .collect(groupingBy(bp -> bp.getDescription().getType()));
Bernie
  • 2,253
  • 1
  • 16
  • 18