Intro Java8 groupingBy Collector

Intro Java8 groupingBy Collector

這篇介紹Intro Java8 groupingBy Collector。

Example Code Setup

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
To demonstrate the usage of groupingBy(), let's define a BlogPost class (we will use a stream of BlogPost objects):

class BlogPost {
String title;
String author;
BlogPostType type;
int likes;
}

Next, the BlogPostType:

enum BlogPostType {
NEWS,
REVIEW,
GUIDE
}

Then the List of BlogPost objects:

List<BlogPost> posts = Arrays.asList( ... );

Let's also define a Tuple class that will be used to group posts by the combination of their type and author attributes:

class Tuple {
BlogPostType type;
String author;
}

Example : Simple Grouping by a Single Column

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

Example : groupingBy with a Complex Map Key Type

1
Map<Tuple, List<BlogPost>> postsPerTypeAndAuthor = posts.stream().collect(groupingBy(post -> new Tuple(post.getType(), post.getAuthor())));