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

84
Vistas
Logging inside Stream

I am trying to convert this piece of code to Java 8 stream:

if (list != null && !list.isEmpty()) {
    Actor actor = null;
    for (Actor actor : list) {
        log.info("Actor being read: "  actor.getCode());
        List<String> areaList = areaDAO.getArea(actor.getCode());
        if (!areaList.isEmpty()) {
            actor.setArea(areaList.get(0));
            log.info("Area{" + areaList.get(0)
                 + "} is fetched for actor{" + actor.getCode() + "}.");
        }
        this.getContext().setReadCount(1);
    }
}

However I am not sure how to deal with logging in this case? Is it a good practice? Appreciate your help. Thanks

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Often we put logging into our code to support debugging. In this case I would recommend you to have a look at the peek method.

Here is a hint:

   List<Actor> actors = ...;

    actors.
        stream().
        peek(a -> System.out.println("Processing code: " + a.getCode())).
        forEach(a -> {/*Do something here*/});

From the javadocs:

API Note: This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline:

about 4 years ago · Santiago Trujillo Denunciar

0

I think that using forEach in this case would be working quite nice for you? Example:

list.stream().forEach(actor -> {
    log.info(String.format("Actor being read {%s}", actor));
    String actorCode = actor.getCode();
    areaDAO.getArea(actorCode).stream().findFirst().ifPresent(area -> {
       actor.setArea(area);
       log.info(String.format("Area {%s} is fetched for actor {%s}", area, actorCode));
    });
    getContext().setReadCount(1);
})

You may want to throw in Objects.isNull() as well in some cases - e.g for that getCode part - as well as Optional.ofNullable?

about 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