How to list, map and “print if count>0” with java 8 / stream api?

  • A+
Category:Languages

Here's my code as per now.

List<Cat> cats = petStore.getCatsForSale();  if (!cats.empty) logger.info("Processing for cats: " + cats.size());  for (Cat cat : cats) {     cat.giveFood(); } 

My colleague writes realy nice code using java-stream api. I tried to rewrite it as one streaming statement, but got stuck.

petStore.getCatsForSale().stream.forEach(cat -> cat.giveFood)     .countTheCats().thenDo(logger.info("Total number of cats: " + x)); // incorrect... is this possible 

Can anyone help? Ideally I want a single streaming statement...

 


Not sure why you want to use streams as the current loop solutions works, but you may aswell 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)); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: