2

I know that ordinary for loops:

List<String> strings = new ArrayList<>();
for (String string : strings) {
    System.out.println("Content: " + string);
}

...can be easily converted to a forEach statement:

List<String> strings = new ArrayList<>();
strings.stream().forEach((string) -> {
    System.out.println("Content: " + string);
});

And hitting Alt+Enter in Netbeans8 IDE converts for loop to forEach but why should we prefer the later one?

  • 1
    This is an opinion-based question. My opinion is that you should not prefer them unless they make the code more readable (which in this case, it isn't), or there is a benefit to parallelizing your stream (again, in this case, there isn't). – RealSkeptic Sep 26 '15 at 10:08
  • `forEach` is not the right way to go. In your example, `peek` should be used. – Tunaki Sep 26 '15 at 10:08
  • 1
    @Tunaki using peek only makes sense if you want to do additional things with the items in the stream and have an action executed when an item is processed, which isn't the case here. In this example `forEach` is the correct equivalent. – Mark Rotteveel Sep 26 '15 at 10:18
  • @Tunaki why? peek() is not even a terminal operation. What would be the terminal operation consuming the stream? – JB Nizet Sep 26 '15 at 10:18
  • Maybe this could help: http://www.javaworld.com/article/2461744/java-language/java-language-iterating-over-collections-in-java-8.html – Tomer Amir Sep 26 '15 at 10:24

0 Answers0