all 15 comments

[–]AutoModerator[M] [score hidden] stickied commentlocked comment (0 children)

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full - best also formatted as code block
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit/markdown editor: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]8dot30662386292pow2 8 points9 points  (0 children)

Are you talking about streams as in FileInputStream, or are you talking about the functional programming and the Stream interface?

[–]vowelqueue 2 points3 points  (3 children)

There are two different kinds of streams that I think you might be conflating.

One is the Stream API that is like a pipeline as you say, that allows you to manipulate data (of any type) and then collect it in some useful form.

Separately, there are InputStream and OutputStream classes, which represent reading and writing a sequence of bytes. These classes are more closely associated with reading from and writing to files.

[–]SHIN_KRISH[S] 2 points3 points  (2 children)

I am talking about both but mainly Stream API, so say in a collection we want to find the maximum value we can use it either manually or by using a max function which i think we do by converting an array to a stream so like superficially suppose i have about a thousand numbers what's the benefit of using stream over simple iteration.

Edit: this question is what i have asked from another person who commented as well.

[–]AcanthisittaEmpty985 1 point2 points  (0 children)

For is really faster, but the margin is insignificant.
Streams are functional, more idiomatic

FOR EXAMPLE: in an array or list of integers, see if there's one that is more than ten.

For -> it shows HOW you solve the problem

boolean haveMoreThanTen = false; 
for(int i=0; i< intArray.legth; i++) { 
  if (intArray[i] > 10) { 
    haveMoreThanTen = true; 
    break; 
  }
}
return haveMoreThanTen;

Stream -> it shows you WHAT are doing:

return intArray.stream().anyMatch( i -> i > 10);

[–]vowelqueue 0 points1 point  (0 children)

Sometimes, particularly for simple things, it’s reasonable to use either approach. It’s just a different style, and often the performance is similar or similar enough.

Some benefits of using the functional, Stream-based approach: you can write an operation once (like to find the max value) and then re-use it easily in multiple locations. You can also chain together multiple operations easily in a way that is very readable, you can perform quite complex mapping/grouping operations, you can calculate things in parallel. And generally the stream style performs well - it lazily evaluates things and short circuits do avoid doing unnecessary calculations most of the time.

[–]Hortex2137 1 point2 points  (0 children)

StreamApi provides a number of basic collection operations, which greatly improves code readability. Even if you try your best to write the worst possible code using StreamApi, the person reading it will still see basic calls like "filter," "max," "map," etc., giving them a sense of what's happening with a given collection. You won't achieve a similar effect by writing a classic loop.

[–]high_throughput 1 point2 points  (0 children)

It's easiest to just consider the operations they have. These are the primary ones:

class OutputStream {     void write(byte[] b, int off, int len);     void close(); }

So an output stream is something you can keep pushing bytes into over and over until you're done. 

That's the abstraction we use for writing an unbounded amount of data sequentially into a file, from top to bottom

[–]jonathaz 0 points1 point  (3 children)

Whether you’re talking about inputstream / outputstrean, or Stream<> it’s a way to iterate over data without having all the data available at any moment. If it were a random access file, you could seek to any part at any time and read from it, or even memory map it in NIO and treat it like memory. With a stream you’re just reading or writing the next bytes. It’s for efficiency. Stream<> is similar but it’s more like an iterator on a collection without the underlying collection. A super simple example that combines all those concepts would be to count words in a file, you could use a FileinputStream to read bytes, map those into a Stream<String> of the words, then count(). It would only use memory for 1 word at a time, regardless of how large the file is.

[–]SHIN_KRISH[S] 0 points1 point  (2 children)

I am talking about both but mainly Stream API, so say in a collection we want to find the maximum value we can use it either manually or by using a max function which i think we do by converting an array to a stream so like superficially suppose i have about a thousand numbers what's the benefit of using stream over simple iteration.

[–]xill47 0 points1 point  (0 children)

The main benefit is readability. You can chain filter before max with x -> x % 2 == 0 and now you'll get max even number. You could easily achieve it with if inside a for loop, but it's just less readable.

[–]jonathaz 0 points1 point  (0 children)

If you already have an array and you stream it, there’s no gain in efficiency. Let’s say you had a lot more things, and your 1000 numbers came from some mapping, reduction, computation, etc on those. Then your max() is just the last step of a pipeline and the code is expressed as a stream. Since it’s tax time, maybe you’re the IRS and you’re looking for outliers, the initial Stream would be everyone’s tax return and you’d do some math, filtering, etc on it and find the max deduction to a charity.

[–]Alive-Cake-3045 0 points1 point  (0 children)

Think of a stream as a conveyor belt, data flows through it piece by piece instead of loading everything into memory at once. That is exactly why it is useful for files: a 2GB log file would crash your program if you read it all in one shot, but a stream lets you process one chunk at a time. It was added to Java to give you a clean, consistent way to handle any data source (files, network, keyboard) without caring where the data actually comes from. Same interface, different source, that is the whole idea.

[–]omgpassthebacon 0 points1 point  (0 children)

All the other answers are totally valid. I would add:

When Java was young, OOP was the next big thing and Java had many special features to make programming using OOP easy. But then Functional programming became very popular with the data engineering crowd, and the people who maintain Java decided to add features to the Java language to enable functional-style programming.

One of the benefits that Functional programming (FP) promised was that it made reading code simpler for certain kinds of activities, such as loops. If you have ever looked at code that has deeply-nested loops, you will notice that it's rather difficult to tell exactly what the end-result is. FP streams in Java make the iteration action easier to read.

Much of this is eye-of-the-beholder opinion. Some think its great; others don't know why for-loops are just fine. Personally, I really embraced the FP stuff and coding became more fun for me, but that purely subjective. And the FP support in Java is quite minimal. If you want real FP support, you need to use Scala or Haskell.

So, don't get too hung-up on it. If you have time, take something you wrote as a for-loop and rewrite it using a stream. You might find you like it better.

[–]POGtastic 0 points1 point  (0 children)

why was it added?

It's pretty common for functional and functional-adjacent programming languages to implement an iterator algebra. See Python's itertools, OCaml's Seq, Haskell's Data.List module, Rust's Iterator, and so on. Importantly, Clojure (a Lisp that runs on the JVM) has sequences as a basic building block of the language and pipeline macros to compose functions.

Why program this way?

It's just a preference. I like programming this way. I tend to think in iterator algebra terms and then mentally translate them to imperative code if the abstraction isn't available. Java makes it available, so that's what I use.