简体   繁体   English

嵌套for Java 8 Stream API表示形式的循环

[英]Nested for loops to Java 8 Stream API representation

Recently I have decided to look into Java 8 by refactoring simple pieces of code. 最近,我决定通过重构简单的代码来研究Java 8。 I have following example which I am trying to convert into Java 8 representation. 我有以下示例,我试图将其转换为Java 8表示形式。

public static void halfTriangle(){
        for(int i=1; i<=4; i++){
            for(int j=1; j<=i; j++){
                System.out.print("* ");
            }
            System.out.println(" ");
        }
    }

I have managed to come up with something like this: 我设法提出了这样的事情:

public static void halfTriangleJava8(){
        IntStream.range(1, 5)
            .forEach(i -> IntStream.range(1, 5)
                .forEach(j -> System.out.println("* "))
        );
    }

but I have no idea where I could place remaining: 但我不知道可以在哪里放置剩余物:

System.out.println(" ");

I have tried something like: 我已经尝试过类似的东西:

public static void halfTriangleJava8(){
        IntStream.range(1, 5)
            .forEach(i -> {
                IntStream.range(1, 5);
                System.out.println(" ");
            }
                .forEach(j -> System.out.println("* "))
        );
    }

But it gives me an error which I don't fully understand. 但这给了我一个我不完全理解的错误。 "The target type for this expression must be a functional interface". “此表达式的目标类型必须是功能接口”。

I believe it's a very simple error but I have only started looking into Java 8 today so any help would be greatly appreciated. 我相信这是一个非常简单的错误,但是我今天才开始研究Java 8,因此将不胜感激。

This is not going to be more elegant but you can have: 这不会更优雅,但您可以:

public static void halfTriangleJava8(){
    IntStream.range(1, 5).forEach(i -> {
        IntStream.rangeClosed(1, i).forEach(j -> System.out.print("* "));
        System.out.println(" ");
    });
}

Althought for those sorts of problems, it'd be better to keep a good-old for loop. 尽管可以解决此类问题,但最好保留一个老版本的for循环。

A somewhat prettier way would be to map each integer into the String to be printed at the corresponding line: 一种更漂亮的方法是将每个整数映射到要在相应行中打印的String

public static void halfTriangleJava8(){
    IntStream.range(1, 5)
             .mapToObj(i -> String.join(" ", Collections.nCopies(i, "*")))
             .forEach(System.out::println);
}

You can add {} braces; 您可以添加{}大括号; and you might use IntStream.rangeClosed(int, int) so you can keep the same indices. 并且您可以使用IntStream.rangeClosed(int, int)以便可以保留相同的索引。 Something like, 就像是,

IntStream.rangeClosed(1, 4).forEach(i -> {
    IntStream.rangeClosed(1, i).forEach(j -> System.out.print("* "));
    System.out.println();
});

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

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