There is a Person
class (with three elements: person_name
, age
, sex
). There is a List
with 100 Person
objects.
I need to search this list by person_name
and implement the search function with a lambda expression.
Java supports lambda expressions but not the Closures. A lambda expression is an anonymous function and can be defined as a parameter.
Lambda functions may be implemented as closures, but they are not closures themselves. This really depends on the context in which you use your application and the environment. When you are creating a lambda function that uses non-local variables, it must be implemented as a closure.
The rule is that a lambda expression can only access local variables from an enclosing scope that are effectively final.
You can think of lambda expressions as anonymous methods (or functions) as they don't have a name. A lambda expression can have zero (represented by empty parentheses), one or more parameters. The type of the parameters can be declared explicitly, or it can be inferred from the context.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With