• Menu
  • Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

JavaBeat

Java Tutorial Blog

  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)

What is an anagram in Java

July 20, 2023 //  by Talha Malik

In Java, an “anagram” works similarly to a palindrome but with a wider scope. It is such that it can check for the strings based on the contained characters either way. This approach comes into effect while omitting duplication from the records. Also, it can be used for identifying the utilized common characters in the strings.

This blog will discuss the concept of Java “anagram”.

What is an “anagram” in Java?

The two strings are considered to be “anagram” if one string can be created by arranging the other string’s characters. Examples include “heart, earth”, “keen, knee” etc. 

Example 1: Checking if a String is Anagram Using the “Arrays” Class

This example applies a check for the anagram strings using the “Arrays” class:

import java.util.*;public class Anagram {
public static void main(String[] args) {
  String firstString = "Heart";
  String secondString = "Earth";
  firstString = firstString.toUpperCase();
  secondString = secondString.toUpperCase();
  if(firstString.length() == secondString.length()) {
  char[] firstcharArray = firstString.toCharArray();
  char[] secondcharArray = secondString.toCharArray();
  Arrays.sort(firstcharArray);
  Arrays.sort(secondcharArray);
  boolean out = Arrays.equals(firstcharArray, secondcharArray);
  if(out == true) {
    System.out.println(firstString + " and " + secondString + " are anagram");
}
  else {
    System.out.println(firstString + " and " + secondString + " are not anagram");
}}
}}

According to the above code:

  • Import the “java.util.*” package to allow working with all the features in the “java.util” package.
  • Initialize the two strings that need to be checked for “anagram”.
  • In the next step, associate the “toUpperCase()” method with both the strings to avoid the case sensitivity while applying the check such that the characters are transformed to uppercase.
  • Now, the “toCharArray()” method transforms both strings into character arrays.
  • Also, sort both the converted character arrays of the strings using the “Arrays.sort()” method.
  • This sorting assists in checking for the contained characters in both strings.
  • Lastly, use the “equals()” method returning a Boolean type to check if the resultant strings are equal and invoke the corresponding “if/else” condition.

Output

This output confirms that both strings are anagrams.

Example 2: Checking if a String is Anagram Using the “StringBuilder” Class

This specific class can also be implemented to apply a check on the passed strings via a user-defined function:

import java.util.*;public class Anagram2 {
public static boolean checkAnagram(String firstString, String secondString) {
  char[] chars = firstString.toCharArray();
  StringBuilder obj = new StringBuilder(secondString);
  for (char x : chars) {
  int index = obj.indexOf("" + x);
  if (index != -1) {
    obj.deleteCharAt(index);
}
  else {
    return false;
}}
  return obj.length() == 0 ? true : false;
}
public static void main(String args[]){
System.out.println(checkAnagram("heart", "earth"));
System.out.println(checkAnagram("keen", "know"));
}}

In this code implementation:

  • Define the function “checkAnagram()” of the Boolean type having the strings as its parameters that need to be passed later as arguments.
  • In its definition, transform the former string into a character array via the “toCharArray()” method.
  • Also, create a StringBuilder object using the “new” keyword and “StringBuilder()” constructor having the latter string as the constructor’s parameter.
  • After that, use the “for” loop and “if/else” conditions in combination to check for the latter string by referring to the former string.
  • It is such that the “indexOf()” method checks for the index of the iterated characters of the latter string and deletes that character if found with respect to the former string.
  • Now, check for the latter string’s length and invoke the corresponding Boolean value.
  • In “main”, invoke the defined function twice by passing the stated strings to be checked for “anagram”.

Output

These Boolean values are returned from the function indicating that the former strings are anagram while it is not the case with the latter ones.

Example 3: Checking if a String is Anagram Using “HashMap”

In this specific demonstration, a “HashMap” can be utilized to check for anagram: 

import java.util.*;public class Anagram3 {
public static boolean checkAnagram(String x, String y){
  if (x.length() != y.length()) {
  return false;
}
  HashMap<Character, Integer> map = new HashMap<>();
  for (int i = 0; i < x.length(); i++) {
  if (map.containsKey(x.charAt(i))) {
    map.put(x.charAt(i),
    map.get(x.charAt(i)) + 1);
}
  else {
    map.put(x.charAt(i), 1);
}}
  for (int i = 0; i < y.length(); i++) {
  if (map.containsKey(y.charAt(i))) {
    map.put(y.charAt(i),
    map.get(y.charAt(i)) - 1);
}
  else {
    return false;
}}
  Set<Character> keys = map.keySet();
  for (Character a : keys) {
  if (map.get(a) != 0) {
    return false;
}}
  return true;
}
public static void main(String[] args){
String firstString = "heart";
String secondString = "earth";
if (checkAnagram(firstString, secondString))
  System.out.print("The Strings " + firstString+" and "+secondString+" are anagram");
else
  System.out.print("The Strings" + firstString+" and "+secondString+" are not  anagram");
}}

In this code snippet:

  • Likewise, define a function having the stated strings to be checked for anagram as its parameters.
  • In the function definition, check for both the passed strings’ length and return “false” if not equal.
  • Also, create a HashMap object, loop along the characters of the former string characters, and append it to HashMap.
  • Analyze if HashMap already contains the iterated character or not. If so, increase the count by “1” for that particular character. Otherwise, place that character on the map and set the count to “1” as the character is faced for the first time. After that, iterate through the latter string.
  • Similarly, check if the iterated character exists in HashMap. If so, reduce the count of that character by “1” to imply that the currently iterated character has been already counted.
  • This is done to ensure that all the characters in the former string are present in the latter string.
  • Now, extract and loop along all the keys of HashMap and check if all keys are “0”. If so, it implies that it is an anagram.
  • Lastly, in “main”, define the stated strings and pass these values to the invoked function to return the corresponding outcome based on the “if/else” conditions. 

Output

This outcome signifies that the defined strings are anagrams.

Conclusion

The two strings are considered to be anagrams if one string can be created by arranging the other string’s characters. This check can be applied using the “Arrays” class, “StringBuilder” class, or via “HashMap”. This blog demonstrated the concept and working of Java “anagram”.

Category: Java

Previous Post: « How to Pass a Local File into URL in Java
Next Post: What is ArrayList iterator() in Java »

Primary Sidebar

Follow Us

  • Facebook
  • Pinterest

FEATURED TUTORIALS

How to Use Optional.ofNullable() Method in Java

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Introductiion to Jakarta Struts

What’s new in Struts 2.0? – Struts 2.0 Framework

JavaBeat

Copyright © by JavaBeat · All rights reserved
Privacy Policy | Contact