Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

237
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda