使用Java 8 Lambda表达式过滤列表 [英] Filtering a list using Java 8 lambda expressions

查看:786
本文介绍了使用Java 8 Lambda表达式过滤列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Project课:

class Project {
    List<Name> names;
    int year;
    public List<Name> getNames(){
        return names;
    }
}

然后我有另一个主要功能,其中有一个List<Project>,并且必须根据年份过滤该项目列表,并获取名称列表作为结果.

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.

您能告诉我如何使用Java 8 Lambda表达式吗?

Can you please tell me how to do it using java 8 lambda expressions?

谢谢

推荐答案

好吧,您没有说明确切的过滤条件,但假设您希望按给定年份过滤元素:

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

这篇关于使用Java 8 Lambda表达式过滤列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆