Select Object from Object' s list using lambda expression

21,443

Solution 1

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.

Solution 2

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:

    1. Right-click on the project and select Properties
    2. Select Java Compiler in the window that has been opened
    3. Under JDK Compliance unselect the Use compliance level from execution environment.... checkbox and then select 1.8 from the Compliance level dropdown.
    4. Click OK and your done.

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);
Share:
21,443
Tinwor
Author by

Tinwor

Updated on April 20, 2021

Comments

  • Tinwor
    Tinwor about 3 years

    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.