How to check if two Strings are Anagrams in Java

In this post, we will see how to check if two Strings are Anagrams in java.

Anagrams mean if two Strings have the same characters but in a different order.
For example: Angel and Angle are anagrams

There are many ways to check if Strings are anagrams in java. Some of them are:

Using String methods

Algorithm:
  1. Pass two Strings word and anagram to method called isAnagramUsingStringMethods()
  2. Iterate over first String word and get char c from it using charAt() method
  3. If index of char c is -1 in second String anagram, then two strings are not anagrams
  4. If index of char c is not equal to -1 in second String anagram, then remove the character from the String anagram.
  5. If you get empty String in the end, then two Strings are anagrams of each other.
When you run above program, you will get below output:

Using Arrays.sort()

You can simply sort both the Strings using Arrays.sort() method. If both the Strings are equal after Sorting, then these two Strings are anagram of each other.

When you run above program, you will get below output:

java2blog and aj2vabgol are anagrams :true

Using count array

Here is another approach to find if two Strings are anagrams.

  1. Pass two Strings str1 and str2 to method isAnagram()
  2. If length of str1 and str2 are not same, then they are not anagrams
  3. Create an array named count of 256 length
  4. Iterate over first string str1
  5. In each iteration, we increment count of first String str1 and decrement the count of second String str2
  6. If count of any character is not 0 at the end, it means two Strings are not anagrams

This approach has time complexity of O(n), but it requires extra space for count Array.

Are Angle and Angel anangrams: true

Using Guava’s Multiset

If you prefer to use Guava library’s inbuild method to check if two String are anagrams, then you can use MultiSet.

MultiSet allows multiple occurrences of each element and tracks the count of each element.

You need to add following dependency to pom.xml.

Here are the steps to use Multiset for checking if two Strings are anagram in Java.

  1. Pass two Strings str1 and str2 to method isAnagram()
  2. If length of str1 and str2 are not same, then they are not anagrams
  3. Create two multisets ms1 and ms2 using HashMultiset.create() method
  4. Iterate over first string str1
  5. In each iteration, add character of first String str1 to ms1 and character of second String str2 to ms2
  6. If ms1 and ms2 are equal after iteration, it means two Strings are not anagrams

Let’s see with the help of Example.

Are Angle and Angel anangrams: true

Other String Programs

That’s all about how to check if two Strings are Anagrams in Java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *