Created
May 7, 2020 16:15
-
-
Save anbusampath/0c9b1a4ecbcc478d1e41a1834a29b795 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.stream.Collectors; | |
public class StreamTest { | |
public static void main(String[] args) { | |
Student student1 = new Student(); | |
student1.dept = "Science"; | |
student1.studentName = "StudentOne"; | |
Student student2 = new Student(); | |
student2.dept = "Science"; | |
student2.studentName = "StudentTwo"; | |
Student student3 = new Student(); | |
student3.dept = "Maths"; | |
student3.studentName = "StudentThree"; | |
Clazz clazz = new Clazz(); | |
clazz.className = "ClassA"; | |
clazz.students = Arrays.asList(student1, student2, student3); | |
School school = new School(); | |
school.schoolName = "ExampleSchool"; | |
school.classes = Arrays.asList(clazz); | |
school.classes.stream() | |
.forEach(StreamTest::processClazz); | |
} | |
static void processClazz(Clazz clazz) { | |
Map<String, List<Student>> studentsByDept = | |
clazz.students.stream() | |
.collect(Collectors.groupingBy(Student::getDept)); | |
Integer count = studentsByDept.entrySet().stream() | |
.map(e -> processStudents(e.getValue())) | |
.reduce(0 ,(partialCount, integer) -> partialCount + integer); | |
System.out.println("Count : " + count); | |
} | |
static Integer processStudents(List<Student> students) { | |
return students.size(); | |
} | |
} | |
class School { | |
String schoolName; | |
List<Clazz> classes; | |
} | |
class Clazz { | |
String className; | |
List<Student> students; | |
} | |
class Student { | |
String dept; | |
String studentName; | |
public String getDept() { | |
return dept; | |
} | |
public void setDept(String dept) { | |
this.dept = dept; | |
} | |
public String getStudentName() { | |
return studentName; | |
} | |
public void setStudentName(String studentName) { | |
this.studentName = studentName; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment