0

Question:

Give a ArrayList of Players - List<Player>. Take a Player POJO with String Name, int age, and int runs. Build a list using list.add.

Find the first player whose age is less than 30 and Runs greater than 5000 and print the name. or else print "No player selected for world cup"

POJO class:

public class Player {
    String name;
    int age;
    int runs;
    
    public Player(String name, int age, int runs) {
        super();
        this.name = name;
        this.age = age;
        this.runs = runs;
    }
    
    @Override
    public String toString() {
        return "Player [name=" + name + "]";
    }
}

Logic:

List<Player> players = Arrays.asList(
    new Player("Sachin",45,10252),
    new Player("Virat",29,7000),
    new Player("Dhoni",38,4000),
    new Player("Yuvraj",29,5500)
);

List<Player> filtered = players.stream()
    .filter(i -> i.runs > 5000 && i.age > 50)
    .collect(Collectors.toList());

if(filtered == null) {
    System.out.println("No Player selected for World Cup");
} else {
    System.out.println(filtered);
}

here the if part is not executing, else is running fine for valid conditions

0

3 Answers 3

6

When using collect(Collection.toList()) the list returned is never null. If there's a filter that no arguments match, the list is empty. You should change your condition to filtered.isEmpty().

Note, however, that the list can be null in a stream.

0
1

This works:

    List<Player> players = Arrays.asList(new Player("Sachin", 45, 10252), new Player("Virat", 29, 7000), new Player("Dhoni", 38, 4000),
            new Player("Viraaat", 28, 7000), new Player("Yuvraj", 29, 5500));
    List<Player> filtered = players.stream().filter(i -> i.runs > 5000 && i.age < 30).collect(Collectors.toList());
    if (filtered.isEmpty())
        System.out.println("No Player selected for World Cup");
    else
        System.out.println(filtered.get(0));
1

The collect() statement will return an array object. You have to check if that array is empty or not.

Also, if you like, you can use the .anyMatch() statement to get a boolean about if there is any match with your filter().

List<Player> players = Arrays.asList(
    new Player("Sachin",45,10252),
    new Player("Virat",29,7000),
    new Player("Dhoni",38,4000),
    new Player("Yuvraj",29,5500)
);

boolean hasPlayers = players.stream().anyMatch(i -> i.runs > 5000 && i.age > 50);
if(!hasPlayers) {
    System.out.println("No Player selected for World Cup");
}
2
  • 2
    But then you have to re-run the filter in case some players match it.
    – Eldar B.
    Commented Sep 5, 2020 at 11:57
  • @EldarB. correct, the usage of this anyMatch depends on the requirements you have. Commented Sep 5, 2020 at 11:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.