Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I list, map and "print if count>0" with Java 8 / stream API?

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...

like image 803
vikingsteve Avatar asked Feb 05 '19 08:02

vikingsteve


People also ask

How do I print List values in stream?

There are 3 ways to print the elements of a Stream in Java: forEach() println() with collect() peek()

Can we use map stream in Java 8?

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.

Can we use stream with map in Java?

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.

How do you use an ArrayList for a stream?

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.


1 Answers

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
like image 198
Naman Avatar answered Oct 08 '22 18:10

Naman