Filtering a list using Java 8 lambda expressions

非 Y 不嫁゛ 提交于 2020-06-22 15:28:12

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/47976942/filtering-a-list-using-java-8-lambda-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!