Stream over a list from Optional

Anshu :

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.

JB Nizet :

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());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=74856&siteId=1