J-J
J-J

Reputation: 5871

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

Upvotes: 4

Views: 10494

Answers (3)

J-J
J-J

Reputation: 5871

A simple way to handle a null list is by using the method:

CollectionUtils.emptyIfNull()

So the code becomes.

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

This ensures that your code avoids null checks, and becomes cleaner:

Upvotes: 0

Naman
Naman

Reputation: 31878

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

Upvotes: 9

John Kugelman
John Kugelman

Reputation: 361585

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.

If you do that then you can just call stream() directly without any of this Optional business:

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

Upvotes: 5

Related Questions