Write a Java program using Lambda Expression to check if a given string is empty


The java program that demonstrates the use of the Predicate functional interface to check if a given string is empty. Here's an explanation of the code:

  • import java.util.function.Predicate;: This line imports the Predicate functional interface from the java.util.function package. A Predicate is a functional interface that represents a boolean-valued function that takes an input and returns true or false.
  • The StringChecker class is defined, which contains the main method, where the program's execution begins.
  • Inside the main method:
    • String inputString = "";: This line initializes a string variable named inputString with an empty string.
    • Predicate<String> isEmpty = str -> str.isEmpty();: This line creates a Predicate named isEmpty that checks if a given string is empty. It uses a lambda expression to implement the test method of the Predicate functional interface.
    • if (isEmpty.test(inputString)): This line uses the test method of the isEmpty Predicate to check if the inputString is empty. If it's empty (i.e., the lambda expression evaluates to true), it prints "String is Empty." Otherwise, it prints "String is Not Empty."

Source Code

import java.util.function.Predicate;
 
public class StringChecker
{
	public static void main(String[] args)
	{
		String inputString = "";
		Predicate<String> isEmpty = str -> str.isEmpty();
		if (isEmpty.test(inputString))
		{
			System.out.println("String is Empty");
		}
		else
		{
			System.out.println("String is Not Empty");
		}
	}
}

Output

String is Empty

Example Programs