如何在 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
How to search a collection using lambda expression in Java?
提问by user3677652
There is a Person
class (with three elements: person_name
, age
, sex
). There is a List
with 100 Person
objects.
有一个Person
类(具有三个元素:person_name
, age
, sex
)。有List
100 个Person
对象。
I need to search this list by person_name
and implement the search function with a lambda expression.
我需要通过person_name
lambda 表达式搜索此列表并实现搜索功能。
回答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 Optional
so 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)
如果您希望在失败的搜索中返回空值,则可以使用。