public class AnagramSolver { public static boolean areAnagrams(String str1, String str2) { String sortedStr1 = sortString(str1); String sortedStr2 = sortString(str2); return sortedStr1.equals(sortedStr2); } private static String sortString(String str) { return Arrays.stream(str.split("")) .sorted() .collect(Collectors.joining()); } public static void main(String[] args) { System.out.println(areAnagrams("listen", "silent")); // Outputs: true System.out.println(areAnagrams("hello", "world")); // Outputs: false } }
In this code, we first sort the characters in each string using a stream. Then we compare the sorted strings. If they are equal, then the original strings are anagrams.
Post a Comment