codebat
codebat

Reputation: 306

Java: Difference between Streams and I/O stream explained

I'm looking for a good explaination of the difference between the "new" Streams in Java 8 and the "old" I/O Streams we had before in Java 7. For someone without any knowledge of functional programming, it's hard to get that those are complete different things, especially because the names are the same. I get that the Stream API is something completely new and even revolutionary in some point, but in my naive thinking, in both cases we deal with sequences of "things", be it bytes, data or objects...

Can someone please offer a good explaination?

Upvotes: 9

Views: 7829

Answers (3)

Uvuvwevwevwe
Uvuvwevwevwe

Reputation: 1041

Let's take a look at the picture illustrated I/O stream.

enter image description here

There are three concerning concepts related to I/O stream: Source, Destination, and Element (represented by the letter 'e'), where

  • Source or Destination could by a file, network connection, pipe, memory buffer etc.
  • An Element is just simply a piece of data and a stream consist of a chunk of elements

When to use what?

I/O streams are for reading content from a source, or writing the content to a destination. That's it, simple :-)

The new Stream concept introduced in Java 8 has nothing to do with I/O streams. Streams are not themselves data structures, but Classes that allow you to manipulate a collection of data in a declarative way (functional-style operation).

Upvotes: 5

Daniel Urbaniak
Daniel Urbaniak

Reputation: 117

In term of 'stream' there is no difference. Stream is abstract phrase that means something that has a source and destination. What is more it is something that represents sequence of data.

In term of these two mechanism there is a lot of differences. For example Java i/o streams let you only read and write data. If you want to process data from that stream there is no builded in mechanism for that. In Java 8 stream there are additional possibilities of processig like map/filter etc.

Upvotes: 3

Silverclaw
Silverclaw

Reputation: 1396

It has nothing to do with each other and I agree, it's bad luck that IO Streams had their name before the "new" Streams have arrived. The I/O streams were meant as connections to external resources, mostly files, but also others. The new Streams are for functional programming and should be treated separately.

But you can actually use both concepts together. For example, a BufferedReader has a lines-method, which returns lines of a file (or other resources) as a Stream of Strings.

Upvotes: 9

Related Questions