4 Ways to Check String is Anagram in Java

In this tutorial I will tell you the four different ways to check string is anagram in Java or not.

Two strings are anagram if they contains same characters in different order. For example word and odwr are anagrams.

 

Ways to Check String is Anagram in Java

 

Ways to Check String is Anagram in Java

Method 1

In this method we sort the strings using Arrays.sort() method and then compare them using Arrays.equals() method. If strings are equal then they are anagram.

 

Output

Enter first string:
adsa

Enter second string:
asad

Strings are Anagram

 

Method 2

In this method we will count the occurrence of each character in first and second string. If the occurrence of characters are equal then strings are anagram.

 

Method 3

In this method we will pick one character form first string and remove it from second string. Repeat the process for all characters. If length of second string is zero that means both the strings are anagram.

I used substring() method of String class to remove the character. We can also use deleteCharAt() method of StringBuilder class.

 

Method 4

In this method I have used HashMap with character as key and integer as value. First pick a character from first string and using this character as key increase the value in hashmap by 1. For second string we will decrease the value in hashmap by 1 for a character as key.

For example character a is encountered in first string so value in hashmap will become 1 for key a. The initial value was 0. Now if same character a is encountered in second string then value will become 0. We will repeat the same process for all the characters in first and second string.

Finally we will check if all the values in hashmap are 0 then the strings are anagram.

 

Please mention in the comment section if you know any other good way to check string is anagram in java.

Leave a Comment

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