javajava-8java-stream

Filter an Optional<List<Object>> in java8


I am trying to Filter an Optional<List<Object>> in Java8. In the below example, I trying to filter the list, without collecting the full list (players). Is this possible?

public List<Player> getPlayers(int age, Team team) {
    Optional.ofNullable(team).map(Team::getPlayers); 
    // needs to filter players older than 20 years, without collecting it as a list.
}

class Team {

    String name;
    List<Player> players;
    public String getName() {
        return name;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public List<Player> getPlayers() {
        return players;
    }

    public void setPlayers(final List<Player> players) {
        this.players = players;
    }

}


class Player {

    String playerName;
    String age;

    public String getPlayerName() {
        return playerName;
    }

    public void setPlayerName(final String playerName) {
        this.playerName = playerName;
    }

    public String getAge() {
        return age;
    }

    public void setAge(final String age) {
        this.age = age;
    }
}

Solution

  • With the updated signature of the method, what you seem to be looking for is:

    public List<Player> getPlayers(Team team, int age) {
        return Optional.ofNullable(team).map(Team::getPlayers)
                .orElse(Collections.emptyList())
                .stream()
                .filter(a -> Integer.parseInt(a.getAge()) > 20)
                .collect(Collectors.toList());
    }