Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a list with a property of an object in the second level list using lambda?

Tags:

lambda

java-8

For example, there are two classes:

class Team { 
 List<Player> players; //with getter & setter
}
class Player{
  String name; //with getter & setter
  int number;  //with getter & setter
}

So, if there are three teams:

Red Team : Adam(4), Tom(5), Peter(11)

Blue Team : Ken(5), Justin(11)

Black Team : Kim(4), Jackal(3)

I want to use lambda to get teams which has a member with jersey number X. For example:

filter with 4 will get Red, Black
filter with 11 will get Red and Blue.

I know how to filter only at player level, like

players.stream().filter(p->p.number.equal(X))

or flatmap to get a list of players

teams.stream().flatmap(t->t.getPlayers())

but how to I mix these lambda to get teams with a property filter on player?

like image 759
Maxi Wu Avatar asked Dec 22 '16 07:12

Maxi Wu


People also ask

How to filter a list by another list Python?

How to Filter a Python List of Lists? Short answer: To filter a list of lists for a condition on the inner lists, use the list comprehension statement [x for x in list if condition(x)] and replace condition(x) with your filtering condition that returns True to include inner list x , and False otherwise.

How do you filter a condition in Java?

The filter() function of the Java stream allows you to narrow down the stream's items based on a criterion. If you only want items that are even on your list, you can use the filter method to do this. This method accepts a predicate as an input and returns a list of elements that are the results of that predicate.

How will you run a filter on a collection?

You can filter Java Collections like List, Set or Map in Java 8 by using the filter() method of the Stream class. You first need to obtain a stream from Collection by calling stream() method and then you can use the filter() method, which takes a Predicate as the only argument.


1 Answers

The solution may look like this:

int playerNumber = ...;
List<Team> filteredTeams = 
    teams
    .stream()
    .filter(
        t -> t.getPlayers().stream().anyMatch(p->p.number==playerNumber)
    )
    .collect(Collectors.toList());
like image 96
Lachezar Balev Avatar answered Oct 17 '22 07:10

Lachezar Balev