Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use forEach with slf4j.logger.info

I am developing a simple application based on Spring Batch, Spring Boot, slf4j and Java 8. I want to use lambda as much as possible for learning purpose. What is wrong with "myPojos.stream()forEach((myPojo)-> {log.info(myPojo);});" below? The message complains "...is not applicable for the arguments <? extends MyPojo". Kindly, note that all other three log lines are working correctly.

public class CustomItemWriter implements ItemWriter<MyPojo> {

    private static final Logger log = LoggerFactory.getLogger(CustomItemWriter.class);

    @Override
    public void write(List<? extends MyPojo> myPojos) throws Exception{
        myPojos.stream().forEach((myPojo)-> {log.info(myPojo);});//error
        myPojos.forEach(System.out::println);//it works
        myPojos.stream().forEach((myPojo) -> {System.out.println(myPojo);}); //it works
        log.info("finish"); //it works
    }

}
like image 878
Jim C Avatar asked Dec 28 '15 21:12

Jim C


2 Answers

Logger.info receives a String, so you have to convert your MyPojo to a string with toString():

myPojos.stream().forEach((myPojo) -> {log.info(myPojo.toString());});

Note that since you have a single statement lambda, you can lose some of the robustness here:

myPojos.stream().forEach(myPojo -> log.info(myPojo.toString()));
like image 83
Mureinik Avatar answered Sep 20 '22 20:09

Mureinik


Java 8 lambda style.
Add @Slf4j at the class level.

myPojos.stream().forEach(log::info);

like image 23
biniam Avatar answered Sep 16 '22 20:09

biniam