What is the benefit to use Stream API instead of for loop in Java 8 if not using parallel stream?
Is it readability? But I think readability of Stream API is not always superior to that of for loop because it depends on the person and situation.
What is the benefit to use Stream API instead of for loop in Java 8 if not using parallel stream?
Is it readability? But I think readability of Stream API is not always superior to that of for loop because it depends on the person and situation.
The main reason to use streams is that they make your code simpler and easy to read. The goal of streams in Java is to simplify the complexity of writing parallel code. It's inspired by functional programming. The serial stream is just to make the code cleaner.
The Stream API is not just an alternative to loops. There are many cases where a regular for
is more suitable. There are also many cases where the Stream API provides more succinct code. It may not be immediately more readable if you're not used to Stream API, but once you learn it, it'll be a lot clearer.
Java Streams API allows declarative style of programming similar to SQL as opposed to imperative style of programming we are all familiar with.
Familiar code is not Readable, Safe code.
int[] nos = new int[10];
for(int i=0;i<10;i++) {
System.out.println(nos[i]);
}
Everyone is familiar with above code but that doesn't necessarily mean it is highly readable and less error prone. You can make alot of mistakes here that can break the code, like initializing i
with 1 instead of 0, using i<=10
for condition instead of i<10
etc.
But with Streams API similar to SQL you are just saying loop and print and I don't care how Java does it.