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 {

    TeamDAO teamDAO;

    PlayerDAO playerDAO;

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

        return player.flatMap(p -> teamDAO.findPlayers(
            .map(p ->


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


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: -> teamDAO.findPlayers(


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 -> teamDAO.findPlayers(
                           .stream().map(tp ->




All Articles