Search code examples
javalambdajava-8log4jslf4j

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 purposes. 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
    }    
}

Solution

  • 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()));