Java 8可选和flatMap - 出了什么问题?

时间:2014-10-08 08:51:06

标签: java map java-8 optional flatmap

一些代码:

public class Player {
    Team team;
    String name;
}

public class Team {
    List<Player> players;
}

public class Demo {

    @Inject
    TeamDAO teamDAO;

    @Inject
    PlayerDAO playerDAO;

    List<String> findTeamMatesNames(String playerName) {
        Optional<Player> player = Optional.ofNullable(playerDAO.get(playerName));

        return player.flatMap(p -> teamDAO.findPlayers(p.team))
            .map(p -> p.name)
            .orElse(Collections.emptyList());
    }
}

为什么我无法做到这一点?在flatMap方法中,我收到错误“类型不匹配:无法从列表转换为可选”

我的目标是:

  1. 如果存在可选项,我想根据此可选对象属性获取项目列表

  2. 如果不存在可选项,我想返回空列表

1 个答案:

答案 0 :(得分:7)

您可以使用map执行所需的操作。如果map为空,则不会进行Optional操作,但会再次留空Optional。您可以在之后提供后备值:

player.map(p -> teamDAO.findPlayers(p.team)).orElse(Collections.emptyList())

List无法执行从Player ListString玩家姓名Optional的映射。这是Stream任务:

Optional<Player> player = Optional.ofNullable(playerDAO.get(playerName));
return player.map(p -> teamDAO.findPlayers(p.team)
                           .stream().map(tp -> tp.name).collect(Collectors.toList()))
             .orElse(Collections.emptyList());