Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream over a list from Optional

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.

like image 452
Anshu Avatar asked Mar 05 '23 11:03

Anshu


2 Answers

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());
like image 175
JB Nizet Avatar answered Mar 16 '23 04:03

JB Nizet


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());
 }
like image 34
Erwin Bolwidt Avatar answered Mar 16 '23 02:03

Erwin Bolwidt