Starts from java 8 to iterate throug list I can use both:
List list = new ArrayList();
1. list.forEach(...)
2. list.stream().forEach(...)
Is it any advantages of using second case? To convert list to stream?
Starts from java 8 to iterate throug list I can use both:
List list = new ArrayList();
1. list.forEach(...)
2. list.stream().forEach(...)
Is it any advantages of using second case? To convert list to stream?
There are no advantages of using the second case, unless you have a parallel stream. There is a disadvantage, namely that Stream.forEach()
doesn't guarantee to respect encounter order. A more accurate (but still unnecessary) equivalent would be Stream.forEachOrdered()
.
No, in theory, the second option is worse than the first one - you pay the cost of instantiation/garbage-collection and calling a Stream
instance and don't really get any benefit in return.
Additionally, in theory the iteration order of Stream.forEach()
isn't deterministic.