0

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.

blackeyedcenter
  • 188
  • 1
  • 12
  • 1
    Welcome to stack overflow! Unfortunately, questions like this are hard to answer because they're so non-specific. The short answer is, yes, for readability. You're right that it depends on situation and taste, but there it is. My advice: learn and become comfortable with them, keep them in mind as you code, and you'll soon discover if/when they're useful to you (and your peers, if you're in a group). And if you don't ever find them useful, don't use them. – yshavit Oct 04 '19 at 08:14
  • Take a look at https://stackoverflow.com/questions/44180101/in-java-what-are-the-advantages-of-streams-over-loops. – rambis Oct 04 '19 at 08:14
  • https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html – Ng Sharma Oct 04 '19 at 08:15
  • @rambis Good find! – yshavit Oct 04 '19 at 08:17

3 Answers3

0

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.

Ng Sharma
  • 2,072
  • 8
  • 27
  • 49
  • 1
    "The goal of streams in Java is to simplify the complexity of writing parallel code." could you provide a source for that claim? – Kayaman Oct 04 '19 at 08:13
0

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.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
0

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.

shazin
  • 21,379
  • 3
  • 54
  • 71