According to what you are showing by your code, you don't have list but a Set, there can be difference in order when iterating over the elements. While for List the order is deterministic, that does not hold true for Set, unless you use specific implementation that guarantees that.
Which should you be using? I think the first question to ask yourself would be what each of those approaches, the Stream forEach() or the Iterable forEach(), is meant for. Why are they there?
First take a look at java.lang.Iterable in the docs. This is the interface which the Collections interface implements, which means that this is the forEach() you use in your second example. What is its purpose?
Java docs wrote: Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Actions are performed in the order of iteration, if that order is specified.
The default implementation behaves as if:
for (T t : this)
Basically we can see that this is provided just as an easy way to iterate over elements (the Iterable interface is mostly used by the Collections API, so most used to iterate over collections). That is what you are trying to do in your example.
In your other example you are using the Stream API to stream the collection and then perform an action for each element. Streams are very powerful for processing data in complex ways or performing many different operations on a sequence of data. You are not getting any benefit from using streams, as you are only iterating over your collection. There is no point using streams for this, especially as there are other methods specifically designed for what you want to do — simply iterating over a collection and doing something with the elements.
Since a stream is used many times, I would also use a stream in the forEach case, for consistency reasons. In the case of OP's set, it also makes it easy to print out the elements in a defined order instead of the randomness that a Set brings. For instance:
I hate signatures!
posted 4 months ago
What is the usage of using with stream() and without stream()...that's what the confusion is
There's no difference that I know of with these two lines:
But if, for instance you wanted to add a filter to print only certain movies, you would need to use the stream. (As Piet pointed out using sorted).
All things are lawful, but not all things are profitable.
posted 4 months ago
What is the usage of Stream and Advantages of Stream ?
What are your superhero powers? Go ahead and try them on this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop