Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 565
Yana Avatar asked Mar 30 '17 06:03

Yana


People also ask

How do you use peek in streams?

Java Stream peek() Java Stream peek() method returns a new Stream consisting of all the elements from the original Stream after applying a given Consumer action. Note that the peek() method is an intermediate Stream operation so, to process the Stream elements through peek() , we must use a terminal operation.

What is peek stream?

In Java, Stream provides an powerful alternative to process data where here we will be discussing one of the very frequently used methods named peek() which being a consumer action basically returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as ...

Can you use streams with primitives?

Streams primarily work with collections of objects and not primitive types. Fortunately, to provide a way to work with the three most used primitive types – int, long and double – the standard library includes three primitive-specialized implementations: IntStream, LongStream, and DoubleStream.

What is peek in API?

peek()'s Javadoc page says: “This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline“.


1 Answers

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:

like image 67
Lachezar Balev Avatar answered Nov 15 '22 19:11

Lachezar Balev