I am trying to understand Lambdas in Java 8.
Say I have a Person class that looks like this:
public class Person implements {
String name;
GenderEnum gender;
int age;
List<Person> children;
}
Now what I want to do is find all persons which are female, that have children that are younger than 10 years old.
Pre java 8 I would do it like this:
List<Person> allPersons = somePeople();
List<Person> allFemaleWithChildren = new ArrayList<>();
for(Person p : allPersons) {
for(Person child : p.getChildren()) {
if(child.getAge() < 10 && p.getGender() == GenderEnum.Female) {
allFemaleWithChildren.add(p);
}
}
}
Now allFemaleWithChildren should have what I want. I have been trying to do the same using streams I think I need to use some sort of map, filter and reduce
allPersons.stream()
//filter females
.filter(p -> p.getGender == GenderEnum.Female)
//get the children
.map(c -> c.getChildren())
//filter the ones that are less than 10 years
.filter(c -> c.getAge() < 10)
//return a list with the result
.collect(Collectors.toList())
But this code does not compile. What am I missing.
Also, I don't understand what the reduce method can be used for.
The compiler says
cannot resolve method getAge(). This is because c is apparently a collection and not the items in the collection, which is really what I want.
Personclass implement ?c.getYear()becausecis a collection and not iterator of the items