Anagram j code example
Example 1: anagram java program
import java.util.Arrays;
public class Anagram
{
public static void main(String[] args)
{
String strOne = "silent";
String strTwo = "listen";
if(strOne.length() == strTwo.length())
{
char[] charOne = strOne.toCharArray();
char[] charTwo = strTwo.toCharArray();
Arrays.sort(charOne);
Arrays.sort(charTwo);
boolean output = Arrays.equals(charOne, charTwo);
if(output)
{
System.out.println(strOne + " and " + strTwo + " are anagram.");
}
else
{
System.out.println(strOne + " and " + strTwo + " are not anagram.");
}
}
else
{
System.out.println(strOne + " and " + strTwo + " are not anagram.");
}
}
}
Example 2: java anagrams
static boolean isAnagram(String a, String b) {
String sortedA = "";
Object[] aArr = a.toLowerCase().chars().sorted().mapToObj(i -> (char) i).toArray();
for (Object o: aArr) {
sortedA = sortedA.concat(o.toString());
}
String sortedB = "";
Object[] bArr = b.toLowerCase().chars().sorted().mapToObj(i -> (char) i).toArray();
for (Object o: bArr) {
sortedB = sortedB.concat(o.toString());
}
if(sortedA.equals(sortedB))
return true;
else
return false;
}