本文介绍了Java 8 Iterable.forEach()与foreach循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java 8中,以下哪个更好?

Java 8:

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

Java 7:

  for(String join:joins){
mIrc.join(mSession,join);



$ b $ p
$ b

我有很多for循环可以用lambdas简化,但是是否真的有使用它们的优势,包括性能和可读性?

编辑

我也将这个问题延伸到更长的方法 - 我知道你不能返回或破坏lambda函数的父函数,这应该被提及,如果他们比较,但还有什么要考虑的?

解决方案

当操作可以并行执行时, (请参阅 - 关于内部和外部迭代的部分)


  • 从我的角度来看,好处是可以定义在循环内执行什么操作,而不必决定它是并行执行还是顺序执行。


  • 如果你想让你的循环并行执行,你可以直接写

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

    您必须为线程处理等编写额外的代码。




注意:
对于我的答案我假设连接执行 java.util。 Stream 界面。如果连接仅实现 java.util.Iterable 接口,则不再成立。

Which of the following is better practice in Java 8?

Java 8:

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

Java 7:

for (String join : joins) {
    mIrc.join(mSession, join);
}

I have lots of for loops that could be "simplified" with lambdas, but is there really any advantage of using them including performance and readability?

EDIT

I'll also extend this question to longer methods - I know that you cant return or break the parent function from a lambda and this should be mentioned to if they are compared, but is there anything else to be considered?

解决方案

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.

这篇关于Java 8 Iterable.forEach()与foreach循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:50