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.
Java: Tips of the Day
How do I remove repeated elements from ArrayList?
If you don't want duplicates in a Collection, you should consider why you're using a Collection that allows duplicates. The easiest way to remove repeated elements is to add the contents to a Set (which will not allow duplicates) and then add the Set back to the ArrayList:
Set<String> set = new HashSet<>(yourList); yourList.clear(); yourList.addAll(set);
Of course, this destroys the ordering of the elements in the ArrayList.
Ref: https://bit.ly/3bYIjNC
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook