如何在Java的Lambda表达式中的两个foreach循环之间打印一条新线
我正在尝试在Java中创建lambda表达式以运行以下线程。我需要做 结果如下。
12345
12345
12345
12345
但是,根据我编写的代码,它是由1234512345123451234512345。我确定了这一点,因为第二次foreach循环之后缺乏println(“”)语句。因此,我尝试编写新的println(“”)语句,但它不起作用。如何解决此问题?我应该在哪里写println(“”)语句?
public class Tb {
public static void main(String[] args) {
// TODO Auto-generated method stub
Runnable r2 = () -> {
IntStream.iterate(1,i-> i+1).limit(5).
forEach(i-> IntStream.iterate(1, j->j+1).limit(5).
forEach(j->{System.out.print(j);})
);
};
new Thread(r2).start();
}
}
I am trying to create a lambda expression in java to run the following thread. I need to make the
outcome as below.
12345
12345
12345
12345
But according to the code I have written it comes as 1234512345123451234512345. I have identified this happens because of the lack of a println("") statement after the second forEach loop. Therefore I tried writting a new println("") statement but it does not work. How can fix this issue? Where should I write the println("") statement here?
public class Tb {
public static void main(String[] args) {
// TODO Auto-generated method stub
Runnable r2 = () -> {
IntStream.iterate(1,i-> i+1).limit(5).
forEach(i-> IntStream.iterate(1, j->j+1).limit(5).
forEach(j->{System.out.print(j);})
);
};
new Thread(r2).start();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需在第二个
intstream
之前添加新行。NB:我还为我的喜好修改了最后的 foreach 。
Just add a new line before the 2nd
IntStream
.NB: I have also modified the last
foreach
for my preference.要在每个foreach循环之后添加线路,需要在第二个foreach之后添加println,例如下面。
`
To add the line after every forEach loop need to add println after the second forEach such as below.
`
只需将您的语句放入curly brackets {} 中,然后添加
println
语句:Just put your statement in your outer
forEach
in curly brackets{}
and add aprintln
statement: