4

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

8
  • What error do you get? Commented Oct 8, 2014 at 8:53
  • What error do you get? And what does teamDAO.finPlayers? Commented Oct 8, 2014 at 8:53
  • Where does team in findTeamMatesNames come from? Commented Oct 8, 2014 at 8:54
  • It's not the point what are you asking for. In flatMap I'am getting: "Type mismatch: cannot convert from List<Player> to Optional<Object>" Commented Oct 8, 2014 at 9:11
  • @coolcfan His code is broken, team should be player. Commented Oct 8, 2014 at 9:25

1 Answer 1

10

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());
Sign up to request clarification or add additional context in comments.

2 Comments

I didn't that I have to perform next operations inside first map function. Thanks!
@dmydlarz: it is also possible to do it afterwards, e.g. player.map(p -> teamDAO.findPlayers(p.team)).orElse(Collections.emptyList()) .stream().map(tp -> tp.name).collect(Collectors.toList()) has the same semantics but it would imply an unnecessary collect operation performed on the empty stream in case of an empty Optional.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.