Skip to content

Commit 05df440

Browse files
committed
groupingBy() collector
1 parent f79ac26 commit 05df440

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
package com.learn.streams_terminal;
2+
3+
import com.learn.data.Student;
4+
import com.learn.data.StudentDataBase;
5+
6+
import java.util.List;
7+
import java.util.Map;
8+
import java.util.stream.Collectors;
9+
10+
/**
11+
* <p>
12+
* groupingBy(): grouping elements according to a
13+
* classification function, and returning the results in a {@code Map<K, V>}
14+
*
15+
* @apiNote There are 3 different versions of groupingBy().
16+
* <ul>
17+
* <li> groupingBy(classifier) : basically what is a classification value that needs to be applied to stream input.</li>
18+
* <li> groupingBy(classifier, downstream) : downstream is another collector of any type </li>
19+
* <li> groupingBy(classifier, supplier, downstream) : supplier which is used to override the default map factory</li>
20+
* </ul>
21+
*
22+
* </p>
23+
* grouping elements according to a
24+
* classification function, and returning the results in a {@code Map}
25+
*/
26+
public class StreamsGroupingByExample {
27+
28+
public static void main(String[] args) {
29+
30+
System.out.println("Student grouped based on Gender : " + groupingByExample1());
31+
System.out.println("Student grouped based on PASS/FAIL : " + groupingByExample2());
32+
}
33+
34+
/**
35+
* <p>
36+
* Group the Student Based on their Gender
37+
* </p>
38+
*/
39+
public static Map<String, List<Student>> groupingByExample1() {
40+
return StudentDataBase.getAllStudents()
41+
.stream()
42+
.collect(Collectors.groupingBy(Student::getGender));
43+
}
44+
45+
46+
/**
47+
* <p>
48+
* grouping Student by using a customized implementation (i.e. based on PASS ond FAIL )
49+
* </p>
50+
* @return
51+
*/
52+
public static Map<String, List<Student>> groupingByExample2() {
53+
return StudentDataBase.getAllStudents()
54+
.stream()
55+
.collect(Collectors.groupingBy(student -> student.getGpa() >= 3.8 ? "PASS" : "FAIL"));
56+
}
57+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ This repository contains the basic &amp; advance level examples related to Java
4848
* [ mapping()](Modern-Java-Examples/src/com/learn/streams_terminal/StreamsMappingExample.java)
4949
* [ minBy() and maxBy()](Modern-Java-Examples/src/com/learn/streams_terminal/StreamsMinByMaxByExample.java)
5050
* [ summingInt() and averagingInt()](Modern-Java-Examples/src/com/learn/streams_terminal/StreamsSumAvgExample.java)
51+
* [ groupingBy()](Modern-Java-Examples/src/com/learn/streams_terminal/StreamsGroupingByExample.java)
5152

5253

5354
<hr />

0 commit comments

Comments
 (0)