简体   繁体   中英

How can I return boolean value using Optional.ifPresent

I have some problems with using Optional.ifPresent statement. I would like to reduce number of NullPointerExceptions , so I decided to use Optional values.

Also I am trying to avoid a ladder of if statements anti-pattern.

So I implemented Optional.isPresent statement. But it's not really that what I expected.

Please look at these listings:

This is a part of my service:

    if (getAllComputerProducers().isPresent()) {
        if (isComputerProducerAlreadyExist(computerProducer))
            return new ResponseEntity<>(HttpStatus.CONFLICT);
    }

    computerProducerRepository.save(computerProducer);
    return new ResponseEntity<>(HttpStatus.CREATED);

getAllComputerProducers function looks like that:

private Optional<List<ComputerProducer>> getAllComputerProducers() {
    return Optional.ofNullable(computerProducerRepository.findAll());
}

As you can see, this function returns Optional of List .

The isComputerProducerAlreadyExist function is implemented like that:

private boolean isComputerProducerAlreadyExist(ComputerProducer computerProducer) {
    return getAllComputerProducers()
            .get()
            .stream()
            .anyMatch(producer -> producer.getProducerName()
                    .equalsIgnoreCase(computerProducer.getProducerName()));
}

It's so much code and I believe that it could be made simpler. My target is to reduce code to one line command like:

getAllCimputerProducers().ifPresent(***and-here-some-anyMatch-boolean-function***)

but I can't insert there a function which returns something. How can I do it?

Regards to everyone :)

You could try something like

private boolean isComputerProducerAlreadyExist(ComputerProducer computerProducer){
    return this.getAllComputerProducers()
            .map((List<ComputerProducer> computerProducers) -> computerProducers.stream()
                    .anyMatch(producer -> producer.getProducerName().equalsIgnoreCase(computerProducer.getProducerName())))
            .orElse(Boolean.FALSE);
}

Or instead of loading all computer producers load only the ones using its name.

private boolean isComputerProducerAlreadyExist(ComputerProducer computerProducer){
    return computerProducerRepository.findByName(computerProducer.getProducerName()).isEmpty();
}

And as far as I know Spring supports also "exist" methods for repositories without even the need to load the Entity.

The following should work, but I don't have anything to compile it.

Predicate<ComputerProducer> cpPredicate = producer -> producer.getProducerName().equalsIgnoreCase(computerProducer.getProducerName());

boolean compProdExists = getAllCimputerProducers().map(list -> list.stream()
                                                                   .filter(cpPredicate)
                                                                   .findFirst()))
                                                  .isPresent();

You can pass the computerProducer.getProducerName() to repository to get the existing record. Method name will be ' findByProducerName(String producerName) ', if producerName has unique constraint, return type will be Optional<ComputerProducer> , else Optional<List<ComputerProducer>> . However, JPA returns empty list instead of null, so optional on list is not required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM