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:
- Pass two Strings
word
and anagram
to method called isAnagramUsingStringMethods()
- Iterate over first String
word
and get char c
from it using charAt()
method
- If index of char c is
-1
in second String anagram
, then two strings are not anagrams
- If index of char c is not equal to -1 in second String
anagram
, then remove the character from the String anagram
.
- If you get empty String in the end, then two Strings are anagrams of each other.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
package org.arpit.java2blog; public class StringAnagramMain { public static void main(String[] args) { String word = "java2blog"; String anagram = "aj2vabgol"; System.out.println("java2blog and aj2vabgol are anagrams :" + isAnagramUsingStringMethods(word, anagram)); } public static boolean isAnagramUsingStringMethods(String word, String anagram) { if (word.length() != anagram.length()) return false; for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); int index = anagram.indexOf(c); // If index of any character is -1, then two strings are not anagrams // If index of character is not equal to -1, then remove the chacter from the // String if (index != -1) { anagram = anagram.substring(0, index) + anagram.substring(index + 1, anagram.length()); } else return false; } return anagram.isEmpty(); } } |
When you run above program, you will get below output:
|
java2blog and aj2vabgol are anagrams :true |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
package org.arpit.java2blog; import java.util.Arrays; public class AnagramUsingSort { public static void main(String[] args) { String word = "java2blog"; String anagram = "aj2vabgol"; System.out.println("java2blog and aj2vabgol are anagrams :" + isAnagramUsingArraySort(word, anagram)); } public static boolean isAnagramUsingArraySort(String word, String anagram) { String sortedWord = sortChars(word); String sortedAnagram = sortChars(anagram); return sortedWord.equals(sortedAnagram); } public static String sortChars(String word) { char[] wordArr = word.toLowerCase().toCharArray(); Arrays.sort(wordArr); return String.valueOf(wordArr); } } |
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.
-
Pass two Strings str1 and str2 to method
isAnagram()
-
If length of str1 and str2 are not same, then they are not anagrams
-
Create an array named
count
of 256 length
-
Iterate over first string
str1
-
In each iteration, we increment count of first String
str1
and decrement the count of second String str2
-
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
package org.arpit.java2blog; public class AnagramCountingMain { public static void main(String args[]) { boolean isAnagram = isAnagram("Angle","Angle"); System.out.println("Are Angle and Angel anangrams: "+isAnagram); } public static boolean isAnagram(String str1, String str2) { if (str1.length() != str2.length()) { return false; } int count[] = new int[256]; for (int i = 0; i < str1.length(); i++) { count[str1.charAt(i)]++; count[str2.charAt(i)]--; } for (int i = 0; i < 256; i++) { if (count[i] != 0) { return false; } } return true; } } |
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
.
|
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>27.1-jre</version> </dependency> |
Here are the steps to use Multiset for checking if two Strings are anagram in Java.
-
Pass two Strings str1 and str2 to method
isAnagram()
-
If length of str1 and str2 are not same, then they are not anagrams
-
Create two multisets
ms1
and ms2
using HashMultiset.create()
method
-
Iterate over first string
str1
-
In each iteration, add character of first String
str1
to ms1
and character of second String str2
to ms2
-
If
ms1
and ms2
are equal after iteration, it means two Strings are not anagrams
Let’s see with the help of Example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
package org.arpit.java2blog; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; public class AnagramMultiSet { public static void main(String args[]) { boolean isAnagram = isAnagramMultiset("Angle","Angle"); System.out.println("Are Angle and Angel anangrams: "+isAnagram); } public static boolean isAnagramMultiset(String str1, String str2) { if (str1.length() != str2.length()) { return false; } Multiset<Character> ms1 = HashMultiset.create(); Multiset<Character> ms2 = HashMultiset.create(); for (int i = 0; i < str1.length(); i++) { ms1.add(str1.charAt(i)); ms2.add(str2.charAt(i)); } return ms1.equals(ms2); } } |
Are Angle and Angel anangrams: true
Other String Programs
That’s all about how to check if two Strings are Anagrams in Java.
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.