The question is more general and is not related to pros and cons of both styles. The question is should I prefer whenever it is possible to use Stream instead of for loops because it is declarative with a good readability?
I was arguing with my colleague about pros and cons of using streams and for loop. I agree that we should prefer streams in 90% of time but I believe there are some cases when it is better to use for loop instead of stream.
For example I needed to perform several operations on collection of elements and these operations could throw Checked Exception. During operating if exception occurres for any element I wanted to quit the execution at all so I used for loop for it and wrapped it in try/catch block. My colleague was not satisfied because result took in two times more lines than If I would use stream instead. I rewrote it by creating own custom functional interfaces that throws checked exception and static methods to convert them into throwing unchecked exception(examples here) and finally it looked like this:
try {
Map<String, String> someResult= elements.stream()
.filter(throwingPredicateWrapper(element-> client.hasValue(element)))
.collect(
Collectors.toMap(Function.identity(),
throwingFunctionWrapper(element -> client.getValue(element))));
return someResult;
} catch (Exception e) {
LOGGER.error("Error while processing", e);
}
He was happy because it took lines of code in two time less.
It is simple example and it does not look so bad but old loop here is more simple and faster way to deal with that case I believe. Should we tend to use Streams everywhere it is possible?