You can use a Map<Character,Integer>
to count the number of occurrences of each character of a String
. If the Map
s generated for two String
s are equal, you'll know that the corresponding String
s are anagrams.
For example (here I used Map<Integer,Long>
instead of Map<Character,Integer>
since it was more convenient):
String one = "animal";
String two = "manila";
Map<Integer,Long> mapOne = one.chars ().boxed().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
Map<Integer,Long> mapTwo = two.chars ().boxed().collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
System.out.println ("Is anagram? " + mapOne.equals(mapTwo));
Output:
Is anagram? true