简体   繁体   English

筛选可选 <List<Object> &gt;在Java8中

[英]Filter an Optional<List<Object>> in java8

I am trying to Filter an Optional<List<Object>> in Java8. 我正在尝试在Java8中过滤Optional<List<Object>> 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;
    }
}

It's a bad idea to have null lists . 空列表是一个坏主意 It's better to simply have empty lists, but always non-null. 最好只包含列表,但总是非空。 That way you don't have to check for null all the time, you can just iterate straight away. 这样,您不必一直检查是否为null,您可以立即进行迭代。

If you do that then you can just call stream() directly without any of this Optional business: 如果这样做,则可以直接调用stream() ,而无需执行任何此Optional业务:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM