Anagram Program In Java Using List

Anagram Program In Java Using List | An anagram is the strings that contain the same set of characters in a different order. It is just a rearrangement of the characters in words. Also see:- Drivers License Exam Java Program

To understand this problem in detail let us go through some examples:- “keep” and “peek”, both words have the same characters but in a different order. Other examples of an anagram are:-

  • state = taste
  • night = thing
  • arc = car
  • bored = robed
  • cat = act
  • elbow = below
  • inch = chin
  • peach = cheap
  • brag = grab

While checking the anagram, we will ignore the case of the string. Therefore we will convert given string into lowercase and perform the remaining operations. We will solve this problem in 4 ways:-

  1. Anagram program in Java using Arrays
  2. Anagram program In Java without using Array
  3. Anagram program In Java using List
  4. Anagram program In Java using HashMap

Anagram Program in Java using Arrays

Here we will convert the string into array of characters and after that compare both arrays. If both array contains the same elements then they are anagram.

Anagram Program in Java using Arrays

import java.util.Arrays;

public class Main {

   public static void isAnagram(String string1, String string2) {
      // remove whitespace
      String str1 = string1.replaceAll("\\s", "");
      String str2 = string2.replaceAll("\\s", "");

      boolean status = true;
      if (str1.length() != str2.length()) {
         status = false;
      } else {
         // convert to array from lowercase string
         char[] arrayS1 = str1.toLowerCase().toCharArray();
         char[] arrayS2 = str2.toLowerCase().toCharArray();

         // sort arrays
         Arrays.sort(arrayS1);
         Arrays.sort(arrayS2);

         // compare arrays
         status = Arrays.equals(arrayS1, arrayS2);
      }

      if (status) {
         System.out.println(string1 + " & " + string2 
                          + " are anagrams");
      } else {
         System.out.println(string1 + " & " + string2 
                          + " are not anagrams");
      }
   }

   public static void main(String[] args) {
      isAnagram("Keep", "Peek");
      isAnagram("Know", "Program");
      isAnagram("Mother In Law", "Hitler Woman");
      isAnagram("Java", "Have");
   }
}

Output:

Keep & Peek are anagrams
Know & Program are not anagrams
Mother In Law & Hitler Woman are anagrams
Java & Have are not anagrams

Anagram Program In Java Without Using Array

We can write the anagram program in Java without using array. We can directly iterate the string using charAt() method and compare the characters. Let us see the anagram program In Java without using array.

Anagram Program In Java Without Using Array

import java.util.Scanner;

public class Main {
   public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);

      System.out.print("Enter First String : ");
      String str1 = scan.nextLine();

      System.out.print("Enter second String : ");
      String str2 = scan.nextLine();

      if (checkAnagram(str1, str2)) {
         System.out.println(str1 + " and " + str2 + " are anagrams");
      } else {
         System.out.println(str1 + " and " + str2 + 
                          " are not anagrams");
      }

      scan.close();
   }

   public static boolean checkAnagram(String string1, String string2) {

      string1 = string1.replaceAll("\\s", "").toLowerCase();
      string2 = string2.replaceAll("\\s", "").toLowerCase();

      if (string1.length() != string2.length()) {
         return false;
      } else {
         for (int i = 0; i < string1.length(); i++) {
            for (int j = 0; j < string2.length(); j++) {
               if (string1.charAt(i) == string2.charAt(j)) {
                  string2 = string2.substring(0, j) + 
                          string2.substring(j + 1);
                  break;
               }
            }
         }

         if (string2.length() == 0) {
            return true;
         } else {
            return false;
         }
      }
   }
}

Output:

Enter First String : kep
Enter second String : pek
kep and pek are Anagrams

Enter First String : cat
Enter second String : act
cat and act are anagrams

Enter First String : Java
Enter second String : Programming
Java and Programming are not anagrams

Write Anagram Program In Java Using List

In the above Java programs we have used array or without array. We can also write anagram program in Java using List. We will convert the original string into list of string with the help of split() method. If we pass dot (“.”) as parameter to the split() method of string class then it gives array of string where each string is character. Example:- “abcd”.split(“.”) => {“a”, “b”, “c”, “d”}. Now we can convert this array to list using Arrays.aslist() method.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Main {

   public static void isAnagram(String string1, String string2) {
      // remove whitespace & convert to lowercase
      String str1 = string1.replaceAll("\\s", "").toLowerCase();
      String str2 = string2.replaceAll("\\s", "").toLowerCase();

      boolean status = true;
      if (str1.length() != str2.length()) {
         status = false;
      } else {
         // convert to list of string from original string
         List<String> list1 = 
               new ArrayList<String>(Arrays.asList(str1.split(".")));
         List<String> list2 = 
               new ArrayList<String>(Arrays.asList(str2.split(".")));

         // sort list
         Collections.sort(list1);
         Collections.sort(list2);

         // compare lists
         status = list1.equals(list2);
      }

      if (status) {
         System.out.println(string1 + " & " + string2 + 
                            " are anagrams");
      } else {
         System.out.println(string1 + " & " + string2 + 
                            " are not anagrams");
      }
   }

   public static void main(String[] args) {
      isAnagram("Keep", "Peek");
   }
}

Output:-

Keep & Peek are anagrams

Anagram Program In Java Using HashMap

We can take the help of HashMap to devlop anagram program in Java. Map will store character as key and count of character as value. We will store count of characters of first string in the map and substract the count of characters of second string. Finally, map should store only 0 as value then only both strings are anagram.

import java.util.HashMap;
import java.util.Set;

public class Main {
   public static boolean isAnagram(String str1, String str2) {
      str1 = str1.replaceAll("\\s", "").toLowerCase();
      str2 = str2.replaceAll("\\s", "").toLowerCase();
      if (str1.length() != str2.length()) {
         return false;
      }

      HashMap<Character, Integer> map = new HashMap<>();

      // store count of character of str1 into map
      for (int i = 0; i < str1.length(); i++) {
         if (map.containsKey(str1.charAt(i))) {
            map.put(str1.charAt(i), map.get(str1.charAt(i)) + 1);
         } else {
            map.put(str1.charAt(i), 1);
         }
      }

      // subtract count of character of str2 into map
      for (int i = 0; i < str2.length(); i++) {
         if (map.containsKey(str2.charAt(i))) {
            map.put(str2.charAt(i), map.get(str2.charAt(i)) - 1);
         }
      }

      // convert map to set 
      Set<Character> keys = map.keySet();
      // check value = 0 or not
      for (Character key : keys) {
         if (map.get(key) != 0) {
            return false;
         }
      }

      return true;
   }

   public static void main(String[] args) {
      String str1 = "listen";
      String str2 = "silent";

      if (isAnagram(str1, str2))
         System.out.print("Both strings are " + "anagram");
      else
         System.out.print("Both strings are " + "not anagram");
   }
}

Output:

Both strings are anagram

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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