Select Object from Object' s list using lambda expression
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.
You can use Java 8 Stream API to return a particular User found by Id in a list. Take a look at this link.
User user = users.stream()
.filter(x -> x.id == id)
.findAny()
.orElse(null);
- Invoke stream() on the list
- Call the filter() method with a proper Predicate
- Call the findAny() construct, which returns the first element that matches the filter predicate wrapped in an Optional if such an element exists
For convenience, we default to null in case an Optional is empty, but this might not always be the best choice for every scenario.
You have two problems.
You have to enable Java 1.8. Compliance Level in Eclipse and successfully import the Java8 specific classes/interfaces. What you have to do is the following:
- Right-click on the project and select
Properties
- Select
Java Compiler
in the window that has been opened - Under
JDK Compliance
unselect theUse compliance level from execution environment....
checkbox and then select1.8
from theCompliance level
dropdown. - Click
OK
and your done.
- Right-click on the project and select
After you do that, you will notice that the return
statement is not compiling. This is because the List
object in Java is not an array, and therefore statements like user[0]
are invalid for lists. What you have to do is:
return user.get(0);