Concatenate strings using Lambda expression in Java
Java Lambda Program: Exercise-10 with Solution
Write a Java program to implement a lambda expression to concatenate two strings.
Sample Solution:
Java Code:
import java.util.function.BiFunction;
public class Main {
public static void main(String[] args) {
// Define the concatenate lambda expression
BiFunction<String, String, String> concatenate = (str1, str2) -> str1 + str2;
// Concatenate two strings using the lambda expression
String string1 = "Good ";
String string2 = "Morning!";
System.out.println("Original strings: " + string1 + ", " +string2);
String result = concatenate.apply(string1, string2);
// Print the concatenated string
System.out.println("\nConcatenated string: " + result);
}
}
Sample Output:
Original strings: Good , Morning! Concatenated string: Good Morning!
Explanation:
In the above exercise -
From the java.util.function package, we import the BiFunction functional interface.
In the main() method, we define a lambda expression using the BiFunction<String, String, String>. This functional interface represents a function that accepts two String arguments and produces a String result.
The lambda expression "concatenate" takes two strings str1 and str2 as input and concatenates them using the + operator.
After defining the lambda expression, we use it to concatenate two strings by calling the apply method on the lambda expression and passing the two strings as arguments. The result is stored in the result variable, which is a String.
Flowchart:
Live Demo:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Java Lambda Exercises Previous: Check prime number using Lambda expression in Java.
Java Lambda Exercises Next: Find maximum and minimum values with Lambda expression in Java.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/lambda/java-lambda-exercise-10.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics