从可选流列表

时间:2018-09-09 06:48:42

标签: java lambda java-8 java-stream

我在下面有一个简单的示例

static class Town  {
    School school;
}

static class School {
    List<Subject> subjects;
}

static class Subject{
    String name;
}

我想实现一种返回给定城镇的主题名称的方法,该城镇也可以为空

    List<String> getSubjectNames(Town town) {
    return Optional.ofNullable(town)
            .map(town1 -> town1.school)
            .map(school -> school.subjects.stream())
            .flatMap(subjects -> )
            ...
     }

您如何正确地将主题流转换为主题以进行地图操作。任何指针将不胜感激。

2 个答案:

答案 0 :(得分:5)

不要使用Optional检查是否为空。那不是它的目的。您所需要的(如果您真的想接受一个空镇)

List<String> getSubjectNames(Town town) {
    if (town == null) {
        return Collections.emptyList();
    }

    return town.getSchool()
               .getSubjects()
               .stream()
               .map(Subject::getName)
               .collect(Collectors.toList());
}

如果您确实有一个可选城镇,基本上您会做同样的事情:

return optionalTown.map(town ->
   town.getSchool()
       .getSubjects()
       .stream()
       .map(Subject::getName)
       .collect(Collectors.toList())
).orElse(Collections.emptyList());

答案 1 :(得分:2)

您可以尝试:

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