Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

235
Visualizações
Java 8 Optional filter only if present

I have a nullable object and I'm trying to throw an exception if the object is not null and does not meet a condition.

I try this way with Optional:

Optional.ofNullable(nullableObject)
    .filter(object -> "A".equals(object.getStatus()))
    .orElseThrow(() -> new BusinessUncheckedException("exception message"));

When the object is not null, it works as I want, but otherwise, it throws the exception too (and I don't want that).

There is a way to do that with Optional or other ways not using if object != null?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Assuming you aren't doing anything with the returned object, you could use ifPresent and pass a Consumer

nullableObject.ifPresent(obj -> {
    if (!"A".equals(obj.getStatus())) {
        throw new BusinessUncheckedException("exception message");
    }
});

Note: As @Pshemo mentioned in the comments, the contract of the Consumer functional interface allows throwing only RuntimeExceptions.

Otherwise, you are better off with a if check as you've mentioned.

IMO, using a filter on Optional for checks like these is not that readable/intuitive. I would prefer,

if (obj != null && !"A".equals(obj.getStatus())) {     
    throw new BusinessUncheckedException("exception message");
}
over 4 years ago · Santiago Trujillo Relatório

0

If you map to null, the Optional becomes empty:

Optional.ofNullable(nullableObject)
    .map(object -> "A".equals(object.getStatus()) ? object : null)
    .ifPresent(object -> { throw new BusinessUncheckedException("exception message"); });
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda