Java 8 Optional and flatMap - what's wrong?

Some part of the 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 can't I do this? In the flatMap method, I get the error "Mismatch type: cannot convert from list to optional"

My goal:

  • If the option is present, I want to get a list of items based on this optional object property

  • If the option is missing, I want to return an empty list

+3


source to share


1 answer


You can use map

to perform the required operation. The operation map

will not execute if Optional

empty, but leave empty again Optional

. After that, you can provide a fallback value:

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

      



Showing off List

on Player

to a List

player's name String

can not be performed with the help Optional

; this is the task 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());

      

+7


source







All Articles