w3resource

Java Lambda expression - Check if string is empty

Java Lambda Program: Exercise-2 with Solution

Write a Java program to implement a lambda expression to check if a given string is empty.

Sample Solution:

Java Code:

// Main.java
import java.util.function.Predicate;

public class Main {
    public static void main(String[] args) {
        // Lambda expression to check if a given string is empty
        Predicate isEmptyString = str -> str.isEmpty();

        // Test cases
        String str1 = ""; // empty string
        String str2 = "Java lambda expression!"; // non-empty string

        // Check if the strings are empty using the lambda expression
		System.out.println("String 1:" + str1);
        System.out.println("String 1 is empty: " + isEmptyString.test(str1));
        System.out.println("\nString 2:" + str2);
		System.out.println("String 2 is empty: " + isEmptyString.test(str2));
    }
}

Sample Output:

String 1:
String 1 is empty: true

String 2:Java lambda expression!
String 2 is empty: false

Explanation:

In the above exercise, we define a Predicate functional interface with a lambda expression to check if a given string is empty. The lambda expression uses the isEmpty() method of the String class to determine if the string is empty.

To check if the strings are empty, we create two test cases, str1 and str2, and use the test() method of the Predicate interface. On the console, the results are displayed.

Flowchart:

Flowchart: Java  Exercises: Check if string is empt.

Live Demo:

Java Code Editor:

Improve this sample solution and post your code through Disqus

Java Lambda Exercises Previous: Sum of two integers.
Java Lambda Exercises Next: Convert list of strings to uppercase and lowercase using 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.

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

 





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