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 the Java stream API. I tried to rewrite it as one streaming statement, but I got stuck.
petStore.getCatsForSale().stream.forEach(cat -> cat.giveFood)
.countTheCats().thenDo(logger.info("Total number of cats: " + x)); // Incorrect... is this possible?
How can I do this? Ideally I want a single streaming statement...
There are 3 ways to print the elements of a Stream in Java: forEach() println() with collect() peek()
Java 8 Stream's map method is intermediate operation and consumes single element forom input Stream and produces single element to output Stream. It simply used to convert Stream of one type to another. Let's see method signature of Stream's map method.
Converting only the Value of the Map<Key, Value> into Stream: This can be done with the help of Map. values() method which returns a Set view of the values contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set. stream() method.
All you need to do is first get the stream from List by calling stream() method, then call the filter() method to create a new Stream of filtered values and finally call the Collectors. toCollection(ArrayList::new) to collect those elements into an ArrayList.
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
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