Lambda expressions basically express instances of functional interfaces (An interface with a single abstract method is called functional interface. An example is java.lang.Runnable). lambda expressions implement the only abstract function and therefore implement functional interfaces.
Given a String, we just need to iterate over characters again the task is to check whether a string contains only alphabets or not for which primarily we will check edge cases whether the string is present or not and should not be null, we will simply return false as there is no way to deal with that string. When the above condition is not fulfilled we will make use of lambda expression method isLetter() to check for only characters are there or not, and will return a corresponding boolean value.
Illustrations:
Input : GeeksforGeeks
Output : True
Input : Geeks4Geeks
Output : False
Input : null
Output : False
Concept: The idea is to use isLetter() method of Character class.
Algorithm:
- Get the string
- Match the string:
- Check if the string is empty or not. If empty, return false
- Check if the string is null or not. If null, return false.
- If the string is neither empty nor null,
then check using Lambda Expression Character::isLetter().
- Return true if matched
Pseudocode for the above-proposed algorithm is as follows:
public static boolean isStringOnlyAlphabet(String str)
{
return ((!str.equals("")) && (str != null) && (str.matches("^[a-zA-Z]*$")));
}
Example:
Java
class GFG {
public static boolean isStringOnlyAlphabet(String str)
{
return (
(str != null ) && (!str.equals( "" ))
&& (str.chars().allMatch(Character::isLetter)));
}
public static void main(String[] args)
{
System.out.println( "Test Case 1:" );
String str1 = "GeeksforGeeks" ;
System.out.println( "Input: " + str1);
System.out.println( "Output: "
+ isStringOnlyAlphabet(str1));
System.out.println( "\nTest Case 2:" );
String str2 = "Geeks4Geeks" ;
System.out.println( "Input: " + str2);
System.out.println( "Output: "
+ isStringOnlyAlphabet(str2));
System.out.println( "\nTest Case 3:" );
String str3 = null ;
System.out.println( "Input: " + str3);
System.out.println( "Output: "
+ isStringOnlyAlphabet(str3));
System.out.println( "\nTest Case 4:" );
String str4 = "" ;
System.out.println( "Input: " + str4);
System.out.println( "Output: "
+ isStringOnlyAlphabet(str4));
}
}
|
Output
Test Case 1:
Input: GeeksforGeeks
Output: true
Test Case 2:
Input: Geeks4Geeks
Output: false
Test Case 3:
Input: null
Output: false
Test Case 4:
Input:
Output: false
Related Articles:
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
01 Sep, 2022
Like Article
Save Article