w3resource

Concatenate strings using Lambda expression in Java


Concatenate Two Strings

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:

Flowchart: Java  Exercises: Check if string is empt.

For more Practice: Solve these Related Problems:

  • Write a Java program to implement a lambda expression that concatenates two strings with a delimiter in between.
  • Write a Java program to create a lambda that concatenates multiple strings from a list into a single sentence.
  • Write a Java program to implement a lambda that conditionally concatenates two strings based on their lengths.
  • Write a Java program to chain lambda expressions to concatenate strings and then convert the result to uppercase.

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.



Follow us on Facebook and Twitter for latest update.