Filtering lists using java 8 lambda expressions
•
Java
I have a project class:
class Project { List<Name> names; int year; public List<Name> getNames(){ return names; } }
Then I have another main function. I have a list < project > and must filter the project list according to the year and get the name list as the result
Can you tell me how to use Java 8 lambda expressions?
thank you
Solution
Well, you don't specify the exact filter criteria, but suppose you want 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
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码