如何在 Java 中使用 lambda 表达式搜索集合?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27892756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:35:39  来源:igfitidea点击:

How to search a collection using lambda expression in Java?

javalambdacollectionsjava-8

提问by user3677652

There is a Personclass (with three elements: person_name, age, sex). There is a Listwith 100 Personobjects.

有一个Person类(具有三个元素:person_name, age, sex)。有List100 个Person对象。

I need to search this list by person_nameand implement the search function with a lambda expression.

我需要通过person_namelambda 表达式搜索此列表并实现搜索功能。

回答by sprinter

public Optional<Person> findPersonByName(final List<Person> list, final String name) {
    return list.stream().filter(p -> p.getName().equals(name)).findAny();
}

It returns an Optionalso you will need to test it to see if a value is present. Or you can use orElse(null)if you prefer to get a null back on a failed search.

它返回一个,Optional因此您需要测试它以查看是否存在值。或者,orElse(null)如果您希望在失败的搜索中返回空值,则可以使用。