Java stream API. Find field of an object matching predicate in one line. Return some default value if not exists

Viewed 2118

For example, we have a simple class with some fields. Let's assume, we have fields called 'name' and 'id'. And I want to get name of an object with specified id and return some defaultName, if there is no such object:

private List<MyObject> myObjects;
public String findFieldById(int id) {
    MyObject matchingObj = myObjects.stream()
                    .filter(m -> m.getId() == id)
                    .findFirst().orElse(null);

    return (matchingObj == null) ? "defaultName" : matchingObj.getName();
}

My question is how can I easily make this check on null in a stream in one line?

2 Answers

You can perform this type of operation in one pipeline by mapping to MyObject::getName after findFirst otherwise provide a default value via orElse.

return myObjects.stream()
         .filter(m -> m.getId() == id)
         .findFirst()
         .map(MyObject::getName)
         .orElse("defaultName");

You are not forced to use streams, a simple java for-loop with an if-statement will do the trick too:

public String findFieldById(int id) {
    // iterate over all objects
    for(MyObject myObject : myObjects){
        // if an object's id matches the given parameter
        if(myObject.getId() == id){
            // we will return its name
            return myObject.getName();
        }
    }
    // if nothing was found we will return the default
    return "defaultName";
}
Related