In this tutorial we will see what is an anagram and check if two strings are anagrams or not in java with examples . There are five different string anagram program in java to valid anagram strings .
What is an Anagram ?
If two strings contain same set of characters but in different order then the two strings are called anagrams.
In other words, two strings are anagram, if character frequency of both strings are identical. All the characters of one string should appear same number of time in other string and their should not be any character which is only present in one string but not in other string.
Example of Anagram :
“mango” and “namgo” are anagram
“keep” and “peek” are anagram
Let’s see various method for check if two strings are anagrams in java .
Anagram Program In Java
Method 1: Check if two strings are anagrams using Sorting
Now we check given string anagram in java using sorting method . In this method we use below algorithm.
Algorithm for Anagram
- Convert the two strings into lowercase and remove all white spaces.
- Convert the two strings into char arrays using toCharArray().
- Sort the two character arrays using sort() method of java.util.Arrays class.
- After sorting, we compare both the arrays using equals() method.
- If both arrays are equal then given strings are anagrams otherwise not .
Let’s implement this algorithms to check anagram strings in java .
import java.util.Arrays;
public class AnagramBySorting {
public static void main(String[] args) {
System.out.println("Given string are anagram :");
if (isAnagram("now", "own")) {
System.out.println("The two strings are"
+ " anagram of each other");
}else {
System.out.println("The two strings are not"
+ " anagram of each other");
}
if (isAnagram("Mother In Law", "Hitler Woman")) {
System.out.println("The two strings are"
+ " anagram of each other");
}else {
System.out.println("The two strings are not"
+ " anagram of each other");
}
if (isAnagram("keep", "peek")) {
System.out.println("The two strings are"
+ " anagram of each other");
}else {
System.out.println("The two strings are not"
+ " anagram of each other");
}
}
public static boolean isAnagram(String str1, String str2) {
String s1 = str1.replaceAll("\\s", "");
String s2 = str2.replaceAll("\\s", "");
boolean status = true;
if (s1.length() != s2.length()) {
status = false;
} else {
char[] ArrayS1 = s1.toLowerCase().toCharArray();
char[] ArrayS2 = s2.toLowerCase().toCharArray();
Arrays.sort(ArrayS1);
Arrays.sort(ArrayS2);
status = Arrays.equals(ArrayS1, ArrayS2);
}
return status;
}
}
Output :
Given string are anagram :
The two strings are anagram of each other
The two strings are anagram of each other
The two strings are anagram of each other
Method 2 : Anagram Program in Java using Count Characters
In this anagram program use below algorithm .
- Convert the two strings into lowercase and remove all white spaces.
- Convert the two strings into char arrays using toCharArray().
- Create two count arrays and initialize with 0 .
- Now For each character in input strings, increment count in the corresponding count array.
- If count arrays are equal then given strings are anagrams otherwise not .
import java.util.Arrays;
public class AnagramByCountCharacters {
public static void main(String args[])
{
String str1 = "keep";
String str2 = "peek";
if (areAnagram(str1, str2))
System.out.println("The two strings are "
+ "anagram of each other");
else
System.out.println("The two strings are not"
+ " anagram of each other");
}
static int NO_OF_CHARS = 256;
static boolean areAnagram(String str1, String str2)
{
str1 = str1.replaceAll("\\s", "");
str2 = str2.replaceAll("\\s", "");
if (str1.length() != str2.length()){
return false;
}else{
char[] arr1 = str1.toLowerCase().toCharArray();
char[] arr2 = str2.toLowerCase().toCharArray();
// Create 2 count arrays and initialize
// all values as 0
int count1[] = new int[NO_OF_CHARS];
Arrays.fill(count1, 0);
int count2[] = new int[NO_OF_CHARS];
Arrays.fill(count2, 0);
int i;
// Now For each character in input strings,
// increment count in the corresponding
// count array
for (i = 0; i < arr1.length;
i++) {
count1[arr1[i]]++;
count2[arr2[i]]++;
}
// Compare count arrays
for (i = 0; i < NO_OF_CHARS; i++)
if (count1[i] != count2[i])
return false;
return true;
}
}
}
Output :
The two strings are anagram of each other
Method 3 : Anagram Java Program Using One Array
We have used two count array in previous example . We use only one array for count in this anagrams java code . There we will increment count in the count array for for each character in input strings and we will decrement count in the count array for for each character in input strings .
- Convert the two strings into lowercase and remove all white spaces.
- Convert the two strings into char arrays using toCharArray().
- Create one count arrays and initialize with 0 .
- For each character in input strings, for one string increment count in the count array and for second string decrement count in the count array .
- If count array have only zero value then given strings are anagrams otherwise not .
import java.util.Arrays;
public class AnagramByCountCharacters2 {
public static void main(String args[])
{
String str1 = "now";
String str2 = "own";
if (areAnagram(str1, str2))
System.out.println("The two strings are "
+ "anagram of each other");
else
System.out.println("The two strings are not "
+ " anagram of each other");
}
static int NO_OF_CHARS = 256;
static boolean areAnagram(String str1, String str2)
{
str1 = str1.replaceAll("\\s", "");
str2 = str2.replaceAll("\\s", "");
if (str1.length() != str2.length()){
return false;
}else{
char[] arr1 = str1.toLowerCase().toCharArray();
char[] arr2 = str2.toLowerCase().toCharArray();
if (arr1.length != arr2.length)
return false;
// Create count arrays and initialize
// all values as 0
int count[] = new int[NO_OF_CHARS];
Arrays.fill(count, 0);
int i;
for (i = 0; i < arr1.length;
i++) {
count[arr1[i]]++;
count[arr2[i]]--;
}
//check value in count array
for (i = 0; i < NO_OF_CHARS; i++)
if (count[i] != 0)
return false;
return true;
}
}
}
Output :
The two strings are anagram of each other
Method 4 : Anagram Program in Java Using Hashmap
In above anagram java code used extra space 256 . We can improve it using hashmap . For each character of first string , increment character count or add count one on first occurrence in hashmap . For each character of second string , decrement character count or remove character if count value is one of character in hashmap . If hasmap size zero then given strings are anagram .
import java.util.HashMap;
public class AnagramUsingHashmap {
public static void main(String args[])
{
String str1 = "keep";
String str2 = "peek";
if (areAnagram(str1, str2))
System.out.println("The two strings are"
+ "anagram of each other");
else
System.out.println("The two strings are not"
+ " anagram of each other");
}
public static boolean areAnagram(String str1, String str2)
{
str1 = str1.replaceAll("\\s", "");
str2 = str2.replaceAll("\\s", "");
if (str1.length() != str2.length()){
return false;
} else {
HashMap<Character, Integer> map = new HashMap<Character, Integer>();
for (int i = 0; i < str1.length(); i++)
{
char c = str1.charAt(i);
if (map.containsKey(c))
map.put(c, map.get(c) + 1);
else
map.put(c, 1);
}
for (int i = 0; i < str2.length(); i++)
{
char c = str2.charAt(i);
if (map.containsKey(c))
{
if (map.get(c) == 1)
map.remove(c);
else
map.put(c, map.get(c) - 1);
} else
return false;
}
if (map.size() > 0)
return false;
return true;
}
}
}
Output :
The two strings are anagram of each other
Method 5 : Anagram Program in Java Using ArrayList
This approach is similar as method one implementation above , except this is use Arraylist instead of array . In this approach we created two list and add each character of given strings in corresponding list . Compare both list using equal , if list are equal then given string are anagram .
import java.util.Collections;
import java.util.List;
public class AnagramUsingArrayList {
public static void main(String args[])
{
String str1 = "keep";
String str2 = "peek";
if (areAnagram(str1, str2))
System.out.println("The two strings are "
+ "anagram of each other");
else
System.out.println("The two strings are not "
+ " anagram of each other");
}
public static boolean areAnagram(String str1, String str2)
{
str1 = str1.replaceAll("\\s", "").toLowerCase();
str2 = str2.replaceAll("\\s", "").toLowerCase();
if (str1.length() != str2.length()){
return false;
} else {
List<Character> list1 = new ArrayList<Character>();
List<Character> list2 = new ArrayList<Character>();
for (int i = 0; i < str1.length(); i++)
{
list1.add(str1.charAt(i));
}
for (int i = 0; i < str2.length(); i++)
{
list2.add(str2.charAt(i));
}
Collections.sort(list1);
Collections.sort(list2);
if (list1.equals(list2))
return true;
else
return false;
}
}
}
Output :
The two strings are anagram of each other
In this tutorial we have learned about what is an anagram , anagrams examples and various string anagram program in java . Now you can do anagram coding in java using multiple methods . anagram program in java is very frequently ask interview question . You should try these java string interview question with example .