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
}
}
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()));
Java 8 lambda style.
Add @Slf4j
at the class level.
myPojos.stream().forEach(log::info);
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