How do I list, map and "print if count>0" with Java 8 / stream API?
Your current code is much better without a stream and can further be cutshort to:
if (!cats.isEmpty()) {
logger.info("Processing for cats: " + cats.size());
}
cats.forEach(Cat::giveFood); // Assuming giveFood is a stateless operation
I am not sure why you want to use streams as the current loop solutions works, but you may as well use a Stream<List<Cat>>
:
Stream.of(petStore.getCatsForSale())
.filter(cats -> !cats.isEmpty())
.flatMap(cats -> {
logger.info("Processing for cats: " + cats.size());
return cats.stream();
})
.forEach(Cat::giveFood);
Maybe an optimization:
Stream.of(petStore.getCatsForSale())
.filter(cats -> !cats.isEmpty())
.peek(cats -> logger.info("Processing for cats: " + cats.size()))
.flatMap(Collection::stream)
.forEach(Cat::giveFood);
Or use this other variant:
Stream.of(petStore.getCatsForSale())
.filter(cats -> !cats.isEmpty())
.mapToInt(cats -> {
cats.forEach(Cat::giveFood);
return cats.size();
})
.findAny()
.ifPresent(count -> logger.info("Processing for cats: " + count));
cats.stream()
.peek(Cat::giveFood)
.findAny().ifPresent(cat -> logger.info("Processing for cats: " + cats.size()));