Home > Software design >  How to print a new line between two forEach loops in lambda expressions in java
How to print a new line between two forEach loops in lambda expressions in java

Time:06-04

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();

    }

}


CodePudding user response:

Just add a new line before the 2nd IntStream.

IntStream.iterate(1, i -> i   1).limit(5).forEach(i -> {
                System.out.println();
                IntStream.iterate(1, j -> j   1).limit(5).forEach(System.out::print);
            });

NB: I have also modified the last foreach for my preference.

CodePudding user response:

To add the line after every forEach loop need to add println after the second forEach such as below.

`

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);

                    });
                    System.out.println();
                });

    };

    new Thread(r2).start();

}

CodePudding user response:

Just put your statement in your outer forEach in curly brackets {} and add a println statement:

public static void main(String[] args) {
    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);
                            });
                    System.out.println();
                });
    };
    new Thread(r2).start();
}
  • Related