I have a Project
class:
class Project {
List<Name> names;
int year;
public List<Name> getNames(){
return names;
}
}
Then I have another main function where I have a List<Project>
and have to filter that list of projects on the basis of year and get names list as the result.
Can you please tell me how to do it using java 8 lambda expressions?
Thanks
Performance. We have seen that using multiple filters can improve the readability of our code.
Well, you didn't state the exact filtering condition, but assuming you wish to filter elements by a given year:
List<Name> names = projects.stream()
.filter(p -> p.getYear() == someYear) // keep only projects of a
// given year
.flatMap(p -> p.getNames().stream()) // get a Stream of all the
// Names of all Projects
// that passed the filter
.collect(Collectors.toList()); // collect to a List
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