Write a Java program using Lambda Expression to concatenate two strings
The java program that concatenates two strings using a lambda expression and the BiFunction functional interface. Here's an explanation of the code:
- import java.util.function.BiFunction;: This line imports the BiFunction functional interface from the java.util.function package. The BiFunction interface represents a function that takes two input values and produces a result.
- The StringConcatenate class is defined, which contains the main method, where the program's execution begins.
- Inside the main method:
- String str1 = "Tutor Joe's"; and String str2 = "Computer Education";: These lines define two string variables, str1 and str2, which hold the strings you want to concatenate.
- BiFunction<String, String, String> concatenate = (s1, s2) -> s1 + " " + s2;: This line defines a BiFunction named concatenate using a lambda expression. The lambda expression takes two string inputs, s1 and s2, and concatenates them with a space in between to create a new string.
- String str_con = concatenate.apply(str1, str2); : This line applies the concatenate lambda expression to the str1 and str2 strings by using the apply method of the BiFunction. It concatenates the two strings and stores the result in the str_con variable.
- System.out.println("Concatenated String : " + str_con);: This line prints the concatenated string.
Source Code
import java.util.function.BiFunction;
public class StringConcatenate
{
public static void main(String[] args)
{
String str1 = "Tutor Joe's";
String str2 = "Computer Education";
BiFunction<String, String, String> concatenate = (s1, s2) -> s1 + " " + s2;
String str_con = concatenate.apply(str1, str2);
System.out.println("Concatenated String : " + str_con);
}
}
Output
Concatenated String : Tutor Joe's Computer Education