一些代码:
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方法中,我收到错误“类型不匹配:无法从列表转换为可选”
我的目标是:
如果存在可选项,我想根据此可选对象属性获取项目列表
如果不存在可选项,我想返回空列表
答案 0 :(得分:7)
您可以使用map
执行所需的操作。如果map
为空,则不会进行Optional
操作,但会再次留空Optional
。您可以在之后提供后备值:
player.map(p -> teamDAO.findPlayers(p.team)).orElse(Collections.emptyList())
List
无法执行从Player
List
到String
玩家姓名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());