Logging inside Stream

你离开我真会死。 提交于 2019-12-06 04:44:42

问题


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

if(list!=null && list.size()>0){
    Actor actor = null;
    for(Actor actor:list){
        log.info("Actor being read: "  actor.getCode());
        List areaList = areaDAO.getArea(actor.getCode());
        if (areaList.size() > 0)
        {
            actor.setArea((String) 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


回答1:


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:




回答2:


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?



来源:https://stackoverflow.com/questions/43109858/logging-inside-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!