Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java Program to Check Strings Anagram Using HashMap
Next article icon

Java Program to Check Strings Anagram Using HashMap

Last Updated : 30 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Java Program to check whether two given strings are anagrams of each other or not using HashMap.

What is an Anagram?

A string is an anagram of another string if it contains the same characters in the same or in different order.

Example of Anagram in Java

Input: s1 = "abcd"
s2 = "cadb"Output: Two Strings are Anagram of each other

Hashmap to Check Anagrams in Java

This method is similar to the frequency array method but this method is optmized since we are not using all the 256 characters, in this method first we iterate in the first string and store the frequency of each character of the first string in the hashmap, then we iterate in the second string and check if the charcter is present in the hashmap or not if it is not present then return a false else reduce the frequency of the character in hashmap by 1 and at last check all the values in the hashmap are zero or not if everything is zero then both strings are anagram else they are not anagrams.

Program to Check Anagram using HashMap:

Java
// Java Program to Check if // String are Anagram using // HashMap import java.io.*; import java.util.*;  // Driver Class class GFG {     // main function     public static boolean is_Anagram(String a, String b)     {         // Length of String Equal or not         if (a.length() != b.length()) {             return false;         }          // Create a HashMap         HashMap<Character, Integer> map = new HashMap<>();          // Using Loop to iterate String         for (int i = 0; i < a.length(); i++) {              if (map.containsKey(a.charAt(i))) {                 // If contains increase count by 1 for that                 // character                 map.put(a.charAt(i),                         map.get(a.charAt(i)) + 1);             }             else {                 // first occurence of the element                 map.put(a.charAt(i), 1);             }         }          // Now loop over String b         for (int i = 0; i < b.length(); i++) {              // Checking current character already             // exists in HashMap             if (map.containsKey(b.charAt(i))) {                 // Maintaing the count in map                 map.put(b.charAt(i),                         map.get(b.charAt(i)) - 1);             }             else {                 return false;             }         }          // Extract all keys of HashMap/map         Set<Character> keys = map.keySet();          // Checking if count of all the elements         // are equal         for (Character key : keys) {             if (map.get(key) != 0) {                 return false;             }         }         // Returning True as all keys are zero         return true;     }     public static void main(String[] args)     {         String str1 = "gram";         String str2 = "arm";          // Function call         if (is_Anagram(str1, str2))             System.out.print("The two strings are "                              + "anagram of each other");         else             System.out.print("The two strings are "                              + "not anagram of each other");     } } 

Output
The two strings are not anagram of each other    

Complexity of the above method

Time Complexity: O(N)
Space Complexity: O(1)


Next Article
Java Program to Check Strings Anagram Using HashMap

H

hardikkushwaha
Improve
Article Tags :
  • Java
  • Java Programs
  • Geeks Premier League
  • Java-Collections
  • Java-Strings
  • Java-HashMap
  • Java-String-Programs
  • Geeks Premier League 2023
Practice Tags :
  • Java
  • Java-Collections
  • Java-Strings

Similar Reads

    Java Program To Check Whether Two Strings Are Anagram
    Write a function to check whether two given strings are anagrams of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other. Program to Check Two Strings
    8 min read
    Java program to count the occurrence of each character in a string using Hashmap
    Given a string, the task is to write a program in Java which prints the number of occurrences of each character in a string. Examples: Input: str = "GeeksForGeeks" Output: r 1 s 2 e 4 F 1 G 2 k 2 o 1 Input: str = "Ajit" Output: A 1 t 1 i 1 j 1 An approach using frequency[] array has already been dis
    2 min read
    Java Program to Find the Occurrence of Words in a String using HashMap
    HashMap<Key, Value> provides the basic implementation of the Map interface of Java and import java.util.HashMap package or its superclass. HashMap stores the data in (Key, Value) pairs, and accessed by an index of another type (e.g. an Integer). One object is used as a key to another object. I
    3 min read
    How to Remove Duplicates from a String in Java Using Hashing?
    Working with strings is a typical activity in Java programming, and sometimes we need to remove duplicate characters from a string. Using hashing is one effective way to do this. By assigning a unique hash code to each element, hashing enables us to keep track of unique items. This article will exam
    2 min read
    Java program to print all duplicate characters in a string
    Given a string, the task is to write Java program to print all the duplicate characters with their frequency Example: Input: str = "geeksforgeeks" Output: s : 2 e : 4 g : 2 k : 2 Input: str = "java" Output: a : 2 Approach: The idea is to do hashing using HashMap. Create a hashMap of type {char, int}
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences