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

  • A+

Here's my code as per now.

List<Cat> cats = petStore.getCatsForSale();  if (!cats.empty)"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("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 -> {"Processing for cats: " + cats.size());         return;     })     .forEach(Cat::giveFood); 

Maybe an optimization:

Stream.of(petStore.getCatsForSale())     .filter(cats -> !cats.isEmpty())     .peek(cats ->"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 ->"Processing for cats: " + count)); 


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