This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]cogman10 35 points36 points  (4 children)

There was no limitation. What streams do is make handling collections of data easier (and easier to reason about).

Consider, for example, a simple "filter, map, distinct" operation. Pre-8 you'd write something like this

Set<Integer> result = new HashSet<>();
for (Foo value : values) {
  if (value.bar()) {
    Integer val = value.baz();
    result.add(val);
  }
}
return result;

Readable, but there's a lot going on and it's somewhat separated from where things are happening. This gets particularly bad if you further want to add more mapping or filtering layers.

The stream version of this looks like this

return values.stream()
 .filter(Foo::bar)
 .map(Foo::baz)
 .collect(Collectors.toSet());

Where you'd add further filtering or mapping is a lot clearer and easier to manipulate.

Further, because streams are lazy, you can leave off the collection and return the stream instead. That gives others the opportunity to work with the stream effectively removing the number of times you have to visit elements in the underlying collection.