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?
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.
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.
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With