Search code examples
javajava-streampolymorphism

How to use Java StreamAPI in this situtation (using polymorphism)


@Override
    public ResultBase handle(Request request) {
        for (Movie movie : this.movieArrayList) {
            if (movie.getTitle().equals(request.getTitle())) {
                return new OkResult(movie);
            }
        }
        return new NotFoundResult();
    } 

I want to apply the STREAM API to the above code

OkResult and NotFoundResult both inherit from the abstract class ResultBase.

The code will return an OkResult if the movie is found in the movie list, and a NotFoundResult otherwise.

public final class OkResult extends ResultBase {
    private final Movie movie;

    public OkResult(final Movie movie) {
        super(ResultCode.OK);

        this.movie = movie;
    }

    public Movie getMovie() {
        return this.movie;
    }
}
public final class NotFoundResult extends ResultBase {
    public NotFoundResult() {
        super(ResultCode.NOT_FOUND);
    }
}
@Override
public ResultBase handle(Request request) {
    return this.movieArrayList.stream()
            .filter(movie -> movie.getTitle().equals(request.getTitle()))
            .map(movie -> new OkResult(movie))
            .findFirst()
            .orElse(new NotFoundResult());
}

My first attempt looks like this But this has a syntax error A compilation error occurred because Optional<OkResult> is required in orElse(new NotFoundResult()).

So I tried fixing the code using polymorphism. The fixed code looks like this

@Override
    public ResultBase handle(Request request) {
        Optional<ResultBase> res = this.movieArrayList.stream()
                .filter(movie -> movie.getTitle().equals(request.getTitle()))
                .map(movie -> (ResultBase) new OkResult(movie))
                .findFirst();

        return res.orElse(new NotFoundResult());
    }

Is there a better way? Thanks for reading this long post


Solution

  • My first attempt looks like this But this has a syntax error A compilation error occurred because Optional is required in orElse(new NotFoundResult()).

    How about using the map method of Optional?

    public ResultBase handle(Request request) {
             return this.movieArrayList.stream()
                 .filter(movie -> movie.getTitle().equals(request.getTitle()))
                 .findFirst().map(movie -> (ResultBase) new OkResult(movie))
                 .orElseGet(NotFoundResult::new);
    }