This question already has answers here:
Java 8 chained method reference?
                                
                                    (1个答案)
                                
                        
                        
                            Comparator.comparing(…) of a nested field
                                
                                    (3个答案)
                                
                        
                                去年关闭。
            
                    
这段代码很简单:

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


BlogPost在哪里:

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


如果BlogPost还有其他一些类作为字段,而我想按这些字段之一分组,例如

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

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


我该如何说

myBlogPost.getDescription().getType()


在lambda表达式中?

伪代码:

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


编辑:
groupingBy是指:

import static java.util.stream.Collectors.groupingBy;

最佳答案

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

10-08 07:05