The method isEmpty() is undefined for the type Optional

Jane Ryan :

I have a spring project where i have a boolean method which uses optional to filter through a set of requests. Im getting an error when i try return request.isEmpty(), I looked it up and i might be using an older version of java but is there any alternative way to say request.isEmpty() without having to update my version of java as Im worried if i update it, it will affect the rest of my project

This is my code for the method

private boolean hasNoDaysOffOnShiftDate(List<Request> requests, ShiftParams params) {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // for string
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // for localdate

    // Shift start date in LocalDate
    String shiftDate = (params.start).format(formatter);
    LocalDate formatDateTime = LocalDate.parse(shiftDate, formatter);
    System.out.println("Shift date in date format " + formatDateTime);

    Optional<Request> request = requests.stream().filter(req -> req.getStatus() == Status.Accepted)
            .filter(req -> isDayOffOnShiftDate(req, formatDateTime)).findAny();
    return request.isEmpty();

}

The error I am getting is

The method isEmpty() is undefined for the type Optional<Request>

I am using this version of java

java.version=1.8.0_73

Andrew Tobilko :

Optional#isEmpty() is a Java 11 method, which is a shortcut for Java 8's !Optional#isPresent().

return !request.isPresent();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=323740&siteId=1