Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Lambda Expressions for repeated String concatenation

The following is an exercise from a lambda expressions tutorial, but I’m kinda stuck at how to do it, since I don’t have much experience with lambda expressions.

I have a functional interface Greeter which has the method greet(Integer n). Now I should write a test to learn how to write lambda expressions. The first test was given:

@Test
void test0() {
  Greeter greeter = (Integer n) -> { return "Hello World!"; };
  assertThat(greeter.greet(1)).isEqualTo("Hello World!");
}

Now, the second test should test that "Hello World! Hello World! Hello World!" is returned when n = 3.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

@Test
void test1() {
  Greeter greeter = null;
  assertThat(greeter.greet(3)).isEqualTo("Hello World! Hello World! Hello World!");
}

How do I concatenate the "Hello World!" with a lambda expression (not a stream)?

>Solution :

You might go like this

Greeter greeter = (Integer n) -> { 
     String s = "Hello World!";
     for(int i = 1; i < n; i++){
       s = " " + s;
     }
     return s;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading