Java 8 Iterable.forEach() vs foreach loop

前端 未结 8 1252
暗喜
暗喜 2020-11-22 14:36

Which of the following is better practice in Java 8?

Java 8:

joins.forEach(join -> mIrc.join(mSession, join));

Java 7:



        
8条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 15:20

    The advantage comes into account when the operations can be executed in parallel. (See http://java.dzone.com/articles/devoxx-2012-java-8-lambda-and - the section about internal and external iteration)

    • The main advantage from my point of view is that the implementation of what is to be done within the loop can be defined without having to decide if it will be executed in parallel or sequential

    • If you want your loop to be executed in parallel you could simply write

       joins.parallelStream().forEach(join -> mIrc.join(mSession, join));
      

      You will have to write some extra code for thread handling etc.

    Note: For my answer I assumed joins implementing the java.util.Stream interface. If joins implements only the java.util.Iterable interface this is no longer true.

提交回复
热议问题