What is an Anagram?
An anagram is a word or phrase formed by rearranging the letters of another word or phrase, using all the original letters exactly once. For example, "listen" and "silent" are anagrams of each other.
Java 8 Program to Check if Two Strings are Anagrams:
In Java 8, we can efficiently check if two strings are anagrams by following these steps:
- Convert both input strings to lowercase to make the comparison case-insensitive.
- Remove spaces from both strings to compare only the characters.
- Convert the strings to character arrays.
- Sort both character arrays.
- Compare the sorted arrays to check if they are equal. If they are equal, the strings are anagrams.
Here's the Java 8 program to achieve this:
import java.util.Arrays;
public class AnagramChecker {
public static boolean areAnagrams(String str1, String str2) {
// Convert to lowercase and remove spaces
str1 = str1.toLowerCase().replaceAll("\\s", "");
str2 = str2.toLowerCase().replaceAll("\\s", "");
// Convert to character arrays
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
// Sort the character arrays
Arrays.sort(charArray1);
Arrays.sort(charArray2);
// Compare the sorted arrays
return Arrays.equals(charArray1, charArray2);
}
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
if (areAnagrams(str1, str2)) {
System.out.println("The strings are anagrams.");
} else {
System.out.println("The strings are not anagrams.");
}
}
}
In this Java 8 program:
- We first preprocess the input strings to remove spaces and make them lowercase.
- We then convert the strings to character arrays.
- Next, we sort both character arrays.
- Finally, we use
Arrays.equals
to compare the sorted arrays. If they are equal, the strings are anagrams.
Comments
Post a Comment