Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select Object from Object' s list using lambda expression

I have a List<User> and I want add a method that return a particular User found using Id. I want make that using lambda expression so I have tried this but it doesn't work.

...
List<User> user = users.stream().filter(x -> x.id == id).collect(Collectors.toList());
return user[0];

This code dosen't compile and give me these errors:

The method stream() is undefined for the type List<User>
Lambda expressions are allowed only at source level 1.8 or above *
Collectors cannot be resolved
  • I'm using eclipse 4.4.3 Kepler and I have installed java 8 in the machine and the plugin for working with java8 in eclipse.
like image 948
Tinwor Avatar asked Jul 17 '14 09:07

Tinwor


People also ask

Which type of object is created in a lambda expression?

Core Java bootcamp program with Hands on practice Yes, any lambda expression is an object in Java. It is an instance of a functional interface. We have assigned a lambda expression to any variable and pass it like any other object.

Can lambda expression contains data type?

The lambda expressions have a very simple, precise syntax and provide flexibility to specify the datatypes for the function parameters.

How do you convert lambda expression to method?

If you are using a lambda expression as an anonymous function but not doing anything with the argument passed, you can replace lambda expression with method reference. In the first two cases, the method reference is equivalent to lambda expression that supplies the parameters of the method e.g. System.

Can lambda expression contains return statement?

A return statement is not an expression in a lambda expression. We must enclose statements in braces ({}). However, we do not have to enclose a void method invocation in braces.


1 Answers

Advice: If you want just first element matchig a condition, don't collect all elements to list (it's a bit overkill), use findFirst() method instead:

return users.stream().filter(x -> x.id == id).findFirst().get();

Note that findFirst() will return an Optional object, and get() will throw an exception if there is no such element.

like image 114
kajacx Avatar answered Oct 15 '22 06:10

kajacx