Denis Stephanov
Denis Stephanov

Reputation: 5281

Find element in ArrayList by conditions and return him or null by lambda

I have collection of custom objects, and I need in my function find the correct one by id property, and return him. If element with that id won't found function return null. Can you help me fix my code? Here is it:

public MyObj find(long id) {
    return myList.stream()
            .filter(obj -> obj.getId() == id)
            .map(obj -> {
                return obj;
            })
            .findFirst()
            .orElse(null);

}

I had error rendundant map call, and part of code with map function is gray. What is wrong with this? Thanks

Upvotes: 1

Views: 775

Answers (1)

Eran
Eran

Reputation: 394016

There's no reason for including the map call, since it's not changing anything (it accepts a MyObj instance and returns the same instance).

public MyObj find(long id) {
    return myList.stream()
            .filter(obj -> obj.getId() == id)
            .findFirst()
            .orElse(null);

}

Upvotes: 3

Related Questions