Search code examples
javafunctional-programmingoption-type

Optional variable take action based on its value


I have a method which takes an Optional parameter and returns a list. I'll populate the list based on whether the Optional parameter is empty or not. What's the most accepted/standard way if any to write the following

public List<ProjectDTO> getProjects(Optional<String> analystId) {
    List<ProjectDTO> projects = new ArrayList<>();

    analystId.ifPresentOrElse(
            t -> projects.addAll(getProjectsByAnalyst(analystId)),
            () -> projects.addAll(getAllProjects())
    );

    return projects;
}

This code works, however I was wondering if there's a better way to do it


Solution

  • Personally, I would not pass an Optional as parameter in this case.

    In this case, I would code it like

    var projects = Optional.of("the-analyst-id")
         .map(id -> getProjectsByAnalist(id))
         .orElseGet(()-> getAllProjects());
    

    You can optionally wrap that in a function (like you did before).

    Method ifPresentOrElse() does not return a value and is mainly an operator meant for running side effects.

    The .map().orElseGet() idiom is the similar, but returns the value.