Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search a collection using lambda expression in Java? [closed]

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.

like image 472
user3677652 Avatar asked Jan 11 '15 22:01

user3677652


People also ask

Are Java lambdas closures?

Java supports lambda expressions but not the Closures. A lambda expression is an anonymous function and can be defined as a parameter.

Are lambda functions closures?

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.

Is it possible to access variables from the outside of a lambda expression?

The rule is that a lambda expression can only access local variables from an enclosing scope that are effectively final.

Can lambda expression have empty bodies?

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.


1 Answers

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.

like image 123
sprinter Avatar answered Nov 03 '22 15:11

sprinter