我有一个Project
类:
class Project {
List<Name> names;
int year;
public List<Name> getNames(){
return names;
}
}
然后,我还有另一个主要功能,我有一个
List<Project>
,并且必须根据年份过滤该项目列表,并获得名称列表作为结果。您能告诉我如何使用Java 8 Lambda表达式吗?
谢谢
最佳答案
好吧,您没有说明确切的过滤条件,但是假设您希望按给定年份过滤元素:
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