Search code examples
javaeclipseis-empty

Getting "The method isEmpty() is undefined for the type Optional" Error in Java File


My Eclipse Java compiler doesn't recognize the isEmpty method in my code. I understand that isEmpty is from Java 1.6, but I'm using 1.8. I've also tried importing org.apache.commons.lang.StringUtils, but that doesn't work. What am I missing?

@Repository("fakeDao") 
public class FakePersonDataAccessService implements PersonDao {
    
    private static List<Person> DB = new ArrayList<>();
    
    @Override
    public int insertPerson(UUID id, Person person) {
        DB.add(new Person(id, person.getName()));
        return 1;
    }

    @Override
    public List<Person> selectAllPeople() {
        return DB;
    }
    
    @Override
    public int deletePersonById(UUID id) {
        Optional<Person> personMaybe = selectPersonById(id);
        if (personMaybe.isEmpty()) {
            return 0;
        }
        DB.remove(personMaybe.get());
        return 1;
    }
    
    @Override
    public Optional<Person> selectPersonById(UUID id) {
        return DB.parallelStream()
                .filter(person -> person.getId().equals(id))
                .findFirst();
    }

    @Override
    public int updatePersonById(UUID id, Person person) {
        return 0;
    }

}

Solution

  • The isEmpty method of Optional was not added until Java 11.

    For Java 8 you will have to use ! isPresent()