过滤java8中的Optional <list <object >>

时间:2019-03-20 21:49:35

标签: java java-8 java-stream

我正在尝试在Java8中过滤Optional<List<Object>>。在下面的示例中,我尝试过滤列表,而不收集完整列表(玩家)。这可能吗?

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

2 个答案:

答案 0 :(得分:4)

这是bad idea to have null lists。最好仅具有列表,但始终为非null。这样一来,您不必一直检查null,就可以立即进行迭代。

如果您这样做,则可以直接致电stream(),而无需从事任何Optional业务:

team.getPlayers().stream()
    .filter(p -> p.getAge() > 20)

答案 1 :(得分:2)

使用方法的更新签名,您似乎正在寻找的是:

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