Java 8 Optional and flatMap - what is wrong?

◇◆丶佛笑我妖孽 提交于 2020-12-03 17:59:29

问题


Some piece of code:

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

Why am I not able to do this? In flatMap method I am getting error "Type mismatch: cannot convert from List to Optional"

My goal is:

  1. If optional is present I want to get list of items based on this optional object property

  2. If optional is not present I want to return empty list


回答1:


You can use map to perform the desired operation. The map operation will not take place if the Optional is empty but leave again an empty Optional. You can provide the fallback value afterwards:

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

The mapping from a List of Player to a List of Player’s name Strings can’t be performed by an Optional; that’s a Stream task:

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


来源:https://stackoverflow.com/questions/26252779/java-8-optional-and-flatmap-what-is-wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!