This is the fourth solution to check whether the given two strings are Anagram are not. This program uses lambda expression with two parameters. The internal logic uses the String’s class methods toCharArray, contentEquals and Array’s sort method
import java.util.Arrays;
import java.util.Scanner;
//Define the functional interface with SAM 'checkForAnagram'
interface Anagram {
public void checkForAnagram(String str1, String str2);
}
public class AnagramCheck {
public static void main(String[] args) {
Scanner inpStr = new Scanner(System.in);
/* Define the Lambda expression for the user defined functional interface */
Anagram Ag = ((str1Val, str2Val) -> {
// Converting the both input strings to sequence of characters array
char[] str1Chars = str1Val.toLowerCase().toCharArray();
char[] str2Chars = str2Val.toLowerCase().toCharArray();
// Sorting the characters of two arrays including with spaces, if any
Arrays.sort(str1Chars);
Arrays.sort(str2Chars);
/*
* Compare the two sorted character array strings, excluding the spaces, after
* converting into lower case for Anagram check
*/
if (String.valueOf(str1Chars).trim().contentEquals(String.valueOf(str2Chars).trim()))
System.out.println("The strings '" + str1Val + "' and '" + str2Val + "' are Anagram");
else
System.out.println("The strings '" + str1Val + "' and '" + str2Val + "' are not Anagram");
});
System.out.println("Enter an input first line of strings");
String str1 = inpStr.nextLine();
System.out.println("Enter an input second line of strings");
String str2 = inpStr.nextLine();
// Calling the functional interface with String arguments
Ag.checkForAnagram(str1, str2);
Ag.checkForAnagram("sample", "amples");
Ag.checkForAnagram("Clears", "Pearls");
inpStr.close();
}
}
Enter an input first line of strings
Dormitory Beds
Enter an input second line of strings
dirty rooms bed
The strings 'Dormitory Beds' and 'dirty rooms bed' are Anagram
The strings 'sample' and 'amples' are Anagram
The strings 'Clears' and 'Pearls' are not Anagram

Leave a reply to Hairstyles Cancel reply