文章目录
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class GroupTest {

public static void main(String[] args){
List<GroupTest> list = new ArrayList<>();
list.add(new GroupTest(1,"AA"));
list.add(new GroupTest(1,"BB"));
list.add(new GroupTest(2,"CC"));
list.add(new GroupTest(3,"33"));
list.add(new GroupTest(3,"44"));
list.add(new GroupTest(2,"55"));
list.add(new GroupTest(2,"66"));

Map<Integer,List<GroupTest>> m1 = list.stream().collect(
Collectors.groupingBy(GroupTest::getAge)
);
Map<Integer,List<String>> m2 = list.stream().collect(
Collectors.groupingBy(GroupTest::getAge,
Collectors.mapping(GroupTest::getTitle,Collectors.toList())
)
);
System.out.println(m1);
System.out.println(m2);
}
Integer age;
String title;

@Override
public String toString() {
return "GroupTest{" +
"age=" + age +
", title='" + title + '\'' +
'}';
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public GroupTest(Integer age, String title) {
this.age = age;
this.title = title;
}

}

输出:

1
2
3
{1=[GroupTest{age=1, title='AA'}, GroupTest{age=1, title='BB'}], 2=[GroupTest{age=2, title='CC'}, GroupTest{age=2, title='55'}, GroupTest{age=2, title='66'}], 3=[GroupTest{age=3, title='33'}, GroupTest{age=3, title='44'}]}

{1=[AA, BB], 2=[CC, 55, 66], 3=[33, 44]}
文章目录