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
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.
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 ...
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.
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“.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With