public class Student {
String name;
int age;
}
I have a list of Student
objects and I need to group them according to specific logic:
- Group all students whose name starts with "A"
- Group all students whose name starts with "P"
- Group all students whose age is greater than or equal to 30
So far I what I have done:
List<Student> students = List.of(
new Student("Alex", 31),
new Student("Peter", 33),
new Student("Antony", 32),
new Student("Pope", 40),
new Student("Michel", 30));
Function<Student, String> checkFunction = e -> {
if (e.getName().startsWith("A")) {
return "A-List";
} else if (e.getName().startsWith("P")) {
return "P-List";
} else if (e.getAge() >= 30) {
return "30's-List";
} else {
return "Exception-List";
}
};
Map<String, List<Student>> result = students.stream().collect(Collectors.groupingBy(checkFunction));
for (var entry : result.entrySet()) {
System.out.println(entry.getKey() + "---");
for (Student std : entry.getValue()) {
System.out.println(std.getName());
}
}
output
A-List---
Alex
Antony
P-List---
Peter
Pope
30's-List---
Michel
I understand this logic what I am following is wrong, that is why the 30's list is not populated correctly. Is it really possible with groupingBy()
?