Anagram Program in Java

In this tutorial, we will write a Java program to check if two given strings are anagrams or not using different methods and techniques. We will cover the following methods in this tutorial:
  • Java Anagram Program using HashMap
  • Java Anagram Program using Sorting
  • Java Anagram Program using Stream API

What is an Anagram?

An anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. For example, the words "listen" and "silent" are anagrams of each other.

Java Anagram Program using HashMap

In this method, we will use a HashMap to check if two given strings are anagrams or not. We will follow the below steps to implement this method:

  1. First we will create a method areAnagrams that takes two strings as input and returns a boolean value.
  2. We will check if the length of both strings is equal or not. If the length of both strings is not equal, then we can say the strings are not anagrams.
  3. We will create a HashMap to store the frequency of each character in the first string.
  4. We will iterate over the second string and decrement the frequency of each character in the HashMap.
  5. If the frequency of any character becomes negative, then the strings are not anagrams.
  6. If all characters have a frequency of zero, then the strings are anagrams.
Here is the Java program to check if two given strings are anagrams using HashMap:
public class AnagramProgram {
    public static boolean areAnagrams(String str1, String str2) {
        if (str1.length() != str2.length()) {
            return false;
        }

        HashMap map = new HashMap<>();
        for (char c : str1.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }

        for (char c : str2.toCharArray()) {
            if (!map.containsKey(c)) {
                return false;
            }
            map.put(c, map.get(c) - 1);
            if (map.get(c) < 0) {
                return false;
            }
        }

        return true;
    }

    public static void main(String[] args) {
        String str1 = "listen";
        String str2 = "silent";
        if (areAnagrams(str1, str2)) {
            System.out.println("The given strings are anagrams.");
        } else {
            System.out.println("The given strings are not anagrams.");
        }
    }
}
Output:
The given strings are anagrams.
You can change the values of str1 and str2 to test the program with different strings.
Time Complexity: O(n) - The time complexity of this method is linear as we are iterating over all the characters of the strings only once.
Space Complexity: O(n) - The space complexity of this method is linear as we are using a HashMap to store the frequency of each characters.

Java Anagram Program using Sorting

In this method, we will use sorting to check if two given strings are anagrams or not. We will follow the below steps to implement this method:

  1. First we will create a method areAnagrams that takes two strings as input and returns a boolean value.
  2. We will check if the length of both strings is equal or not. If the length of both strings is not equal, then we can say the strings are not anagrams.
  3. We will convert both strings to character arrays and sort them.
  4. We will compare the sorted arrays of both strings. If the sorted arrays are equal, then the strings are anagrams.
Here is the Java program to check if two given strings are anagrams using sorting:
import java.util.Arrays;

public class AnagramProgram {
    public static boolean areAnagrams(String str1, String str2) {
        if (str1.length() != str2.length()) {
            return false;
        }

        char[] arr1 = str1.toCharArray();
        char[] arr2 = str2.toCharArray();

        Arrays.sort(arr1);
        Arrays.sort(arr2);

        return Arrays.equals(arr1, arr2);
    }

    public static void main(String[] args) {
        String str1 = "listen";
        String str2 = "silent";

        if (areAnagrams(str1, str2)) {
            System.out.println("The given strings are anagrams.");
        } else {
            System.out.println("The given strings are not anagrams.");
        }
    }
}
Output:
The given strings are anagrams.
You can change the values of str1 and str2 to test the program with different strings.
Time Complexity: O(n log n) - The time complexity of this method is n log n as we are sorting the arrays.
Space Complexity: O(n) - The space complexity of this method is linear as we are using character arrays to store the characters of the strings.

Java Anagram Program using Stream API

In this method, we will use the Stream API to check if two given strings are anagrams or not. We will follow the below steps to implement this method:

  1. First we will create a method areAnagrams that takes two strings as input and returns a boolean value.
  2. We will check if the length of both strings is equal or not. If the length of both strings is not equal, then we can say the strings are not anagrams.
  3. We will convert both strings to character arrays and sort them.
  4. We will compare the sorted arrays of both strings using the Stream API. If the sorted arrays are equal, then the strings are anagrams.
Here is the Java program to check if two given strings are anagrams using the Stream API:
import java.util.Arrays;

public class AnagramProgram {
    public static boolean areAnagrams(String str1, String str2) {
        if (str1.length() != str2.length()) {
            return false;
        }

        char[] arr1 = str1.toCharArray();
        char[] arr2 = str2.toCharArray();

        return Arrays.equals(
                Arrays.stream(arr1).sorted().toArray(),
                Arrays.stream(arr2).sorted().toArray()
        );
    }

    public static void main(String[] args) {
        String str1 = "listen";
        String str2 = "silent";
        
        if (areAnagrams(str1, str2)) {
            System.out.println("The given strings are anagrams.");
        } else {
            System.out.println("The given strings are not anagrams.");
        }
    }

}
Output:
The given strings are anagrams.
You can change the values of str1 and str2 to test the program with different strings.
Time Complexity: O(n log n) - The time complexity of this method is n log n as we are sorting the arrays.
Space Complexity: O(n) - The space complexity of this method is linear as we are using character arrays to store the characters of the strings.

Which method is best

The best method to check if two given strings are anagrams or not depends on the requirements and constraints of the problem. Here are some points to consider while choosing the best method:

  • HashMap: This method is best when you want to check if two strings are anagrams in a single pass and you want to store the frequency of each character.
  • Arrays: This method is best when you want to check if two strings are anagrams in a single pass and you want to store the frequency of each character in an array.
  • Sorting: This method is best when you want to check if two strings are anagrams in a single pass and you want to sort the characters of the strings.
  • Frequency Count: This method is best when you want to check if two strings are anagrams in a single pass and you want to store the frequency of each character in an array.
  • Stream API: This method is best when you want to check if two strings are anagrams in a single pass and you want to use the Stream API to sort the characters of the strings.
Next we will learn about Java Array Programs.