I have a simple example below
static class Town {
School school;
}
static class School {
List<Subject> subjects;
}
static class Subject{
String name;
}
I would like to implement a method that returns Names of the subjects for a given Town, the town can be null as well
List<String> getSubjectNames(Town town) {
return Optional.ofNullable(town)
.map(town1 -> town1.school)
.map(school -> school.subjects.stream())
.flatMap(subjects -> )
...
}
How do you correctly convert subjectstream to subject for map operations. Any pointers would be appreciated.
Don't use Optional to check for null. That's not what it's for. All you need (if you really want to accept a null town) is
List<String> getSubjectNames(Town town) {
if (town == null) {
return Collections.emptyList();
}
return town.getSchool()
.getSubjects()
.stream()
.map(Subject::getName)
.collect(Collectors.toList());
}
If you really had an Optional town, you would basically do the same thing:
return optionalTown.map(town ->
town.getSchool()
.getSubjects()
.stream()
.map(Subject::getName)
.collect(Collectors.toList())
).orElse(Collections.emptyList());
You can try:
List<String> getSubjectNames(Town town) {
return Optional.ofNullable(town)
.map(town1 -> town1.school)
.map(school -> school.subjects.stream().map(Subject::getName))
.orElse(Stream.empty())
.collect(Collectors.toList());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With