How to check the two strings or sentences are Anagram using HashMap

This is the third solution to check whether the given two strings are Anagram are not. This program uses Hash Map collection.

import java.util.HashMap;
import java.util.Scanner;

public class CheckAnagramUsingHashMap {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		HashMap<Character,Integer> charCntOfStr1,charCntOfStr2 = new HashMap<Character,Integer>();
		Scanner inpStr=new Scanner(System.in);
		//Taking here input from the user the two lines
		System.out.println("Enter first sentence");
		String firstSentence=inpStr.nextLine();
		System.out.println("Enter second sentence");
		String secondSentence=inpStr.nextLine();
		inpStr.close();
		//Pass each line here to get the hashmap of all characters
		charCntOfStr1=getMapOfSentence(firstSentence);
		charCntOfStr2=getMapOfSentence(secondSentence);
		if(charCntOfStr1.equals(charCntOfStr2))
			System.out.println("Both input lines are Anagram");
		else
			System.out.println("Both input lines are not Anagram");
	}

	private static HashMap<Character, Integer> getMapOfSentence(String inpSentence) {
		// TODO Auto-generated method stub

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

		//Return the Hash Map of all characters excluding the While Space if any in between the sentence
		for (int i=0;i<inpSentence.length();i++) {
			char eachChar=Character.toLowerCase(inpSentence.charAt(i));
			if(Character.isWhitespace(eachChar))
				continue;
			else if(!charCntOfStr.containsKey(eachChar))
				charCntOfStr.put(eachChar, 1);
			else
				charCntOfStr.put(eachChar, charCntOfStr.get(eachChar)+1);
		}
		return charCntOfStr;
	}
}
Output:
Enter first sentence
Triangle pin
Enter second sentence
nip integral
Both input lines are Anagram

Comments

Leave a comment