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 means if two String have same characters but in different order.
For example:  Angel and Angel are anagrams

There are many ways to check if Strings are anagrams. Some of them are:
  1. Using String methods
  2. Using array.sort

Using String methods:

Approach :
  1. If index of any character is -1, then two strings are not anagrams
  2. If index of character is not equal to -1, then remove the character from the String.
  3. If you get empty String in the end, then two Strings are anagrams of each other.
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 Array.sort

package org.arpit.java2blog;

import java.util.Arrays;

public class StringAnagramMain {

 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

Other String Programs:

    How to reverse String in java How to check if two Strings are angrams Find length of String without using java inbuilt length method Find all substrings of String in java Find First non repeated character in a String Java Program to check Palindrome String Why String is immutable in java Find duplicate characters in String

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012