简体   繁体   English

这是IntStream嵌套循环的最佳选择吗?错误是什么?

[英]Is this the best option for IntStream nested loops and what is the error?

I want to create a triple nested iteration of numbers from 0 to 500, stepping by 10. 我想创建一个从0到500的数字三重嵌套迭代,以10为步长。

I tried the following and I get an error on the closing round brackets. 我尝试了以下操作,但在右方括号中出现错误。 Can you please advise? 你能给些建议么?

Thank you. 谢谢。

public class App {
    public static void main(String[] args) {

        IntStream.rangeClosed(0, 500).filter(a -> a % 10 == 0).forEach( a ->
                IntStream.rangeClosed(0, 500).filter(b -> b % 10 == 0).forEach( b ->
                        IntStream.rangeClosed(0, 500).filter(c -> c % 10 == 0).forEach( c->
                                System.out.println(a + ", " + b + ", " + c);
                        );
                );
        );
    }
}

Instead of generating 501 elements in each stream and then filtering all the elements not divisible by 10, you can generate IntStream s that contain only multiples of 10: 您可以生成仅包含10的倍数的IntStream ,而不是在每个流中生成501个元素,然后过滤所有不被10整除的元素,而不是:

IntStream.iterate(0, i->i+10).limit(51).forEach( a ->
            IntStream.iterate(0, i->i+10).limit(51).forEach( b ->
                    IntStream.iterate(0, i->i+10).limit(51).forEach( c->
                            System.out.println(a + ", " + b + ", " + c)
                    )
            )
);

My suggestion is: 我的建议是:

    IntStream.rangeClosed(0, 50)
            .forEach(a -> IntStream.rangeClosed(0, 50)
                    .forEach(b -> IntStream.rangeClosed(0, 50)
                            .forEach(c -> System.out.format("%3d, %3d, %3d%n",
                                    a * 10, b * 10, c * 10))));

Excerpt from output: 摘录自输出:

  0,   0,   0
  0,   0,  10
  0,   0,  20
  0,   0,  30
  0,   0,  40

…
500, 500, 490
500, 500, 500

The limit(51) in Eran's answer looks a little bit funny. Eran的答案中limit(51)看起来有点可笑。

What went wrong in your code? 您的代码出了什么问题? As Eran said in a comment , you cannot have semicolon, ; 正如Eran在评论中所说,您不能使用分号; , after method invocations inside your stream (unless surrounded by curly braces). ,方法在流中调用之后(除非用花括号括起来)。 Just remove the first three semicolons, and your code works. 只要删除前三个分号,您的代码就可以使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM