Introduction
An anagram is a word or phrase formed by rearranging the letters of another, typically using all the original letters exactly once. For example, the words "listen" and "silent" are anagrams of each other. Determining whether two strings are anagrams is a common problem in programming, especially in text analysis and cryptography. In this guide, we’ll explore how to use Java 8 Streams to check if two strings are anagrams.
Problem Statement
The task is to create a Java program that:
- Accepts two strings as input.
- Uses Java 8 Streams to check if the two strings are anagrams of each other.
- Outputs whether the strings are anagrams or not.
Example 1:
- Input:
"listen","silent" - Output:
The strings are anagrams.
Example 2:
- Input:
"hello","world" - Output:
The strings are not anagrams.
Solution Steps
- Input Strings: Start with two strings that can either be hardcoded or provided by the user.
- Normalize the Strings: Convert both strings to lowercase and remove any whitespace to ensure case and spacing do not affect the comparison.
- Sort the Characters: Convert each string into a stream of characters, sort them, and then collect the result into a string.
- Compare the Sorted Strings: Check if the sorted versions of the two strings are equal.
- Display the Result: Print whether the strings are anagrams or not.
Java Program
Java 8 Program to Check if Two Strings are Anagrams
import java.util.Arrays;
/**
* Java 8 Program to Check if Two Strings are Anagrams
* Author: https://www.rameshfadatare.com/
*/
public class AnagramCheck {
public static void main(String[] args) {
// Step 1: Take input strings
String str1 = "listen";
String str2 = "silent";
// Step 2: Check if the strings are anagrams
boolean areAnagrams = areAnagrams(str1, str2);
// Step 3: Display the result
if (areAnagrams) {
System.out.println("The strings are anagrams.");
} else {
System.out.println("The strings are not anagrams.");
}
}
// Method to check if two strings are anagrams
public static boolean areAnagrams(String str1, String str2) {
// Normalize the strings
String normalizedStr1 = str1.toLowerCase().replaceAll("\\s", "");
String normalizedStr2 = str2.toLowerCase().replaceAll("\\s", "");
// Sort the characters and compare
return Arrays.equals(
normalizedStr1.chars().sorted().toArray(),
normalizedStr2.chars().sorted().toArray()
);
}
}
Explanation of the Program
-
Input Handling: The program uses two predefined strings
"listen"and"silent"as inputs. You can modify this to accept user input if needed. -
Normalization: Both strings are converted to lowercase using
toLowerCase()to ensure case-insensitivity. Spaces are removed usingreplaceAll("\\s", "")to ensure the comparison is based solely on the letters. -
Sorting and Comparing: The
chars()method converts the strings into streams of characters. These streams are then sorted, converted back into arrays, and compared usingArrays.equals(). -
Output: The program prints whether the two strings are anagrams based on the comparison.
Output Example
Example 1:
Input: listen, silent
Output: The strings are anagrams.
Example 2:
Input: hello, world
Output: The strings are not anagrams.
Advanced Considerations
-
Handling Special Characters: The program currently ignores spaces but considers other special characters. You can extend the normalization step to remove punctuation or other non-alphabetic characters if required.
-
Performance Considerations: The sorting step makes this approach O(n log n) in complexity, which is efficient for typical use cases. For very large strings, other methods like character frequency counting might be more efficient.
-
Case Sensitivity: By default, the program is case-insensitive. If case sensitivity is needed, you can remove the
toLowerCase()call in the normalization step.
Conclusion
This Java 8 program provides an efficient way to check if two strings are anagrams using streams. By sorting the characters and comparing them, you can quickly determine if two strings are rearrangements of each other. This approach is clear, concise, and leverages the functional programming features introduced in Java 8, making it used for text processing tasks.