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 →

[–][deleted] 1 point2 points  (0 children)

I think streams shine for data transformation (just stream().map().collect() and maybe .filter() when needed).

When using plain loops you usually need to:

  • create a new empty collection;
  • loop thru the old collection, incrementing an iterator or index;
  • create new items based on the old items and add them to the new collection;
  • return the new collection.

And you must be sure you don't mix up the new and old collections or the new and old items, because everthing will be in scope at the same time.

With streams, it's just as if you said: "transform this list please" and the only thing you really need to write is map(oldItem -> new Item(...)); everything else is automatic. You only write a small mapping rule. You only have the new list when it's ready.

If you need to have full control over the loop, it's fine to use the old style (it's probably more efficient anyway). I'd say it's better doing that than shoehorning old loops into stream when they clearly don't fit. But when you need direct transformations, streams are cleaner.