Thursday, November 12, 2020

Java: Solving Anagrams with streams

I have been playing with code problems. Since I'm studying for Java 11 certification, I decided to resolve the Anagrams problem using streams. Here what I do is sort the two strings characters and then making a comparison.


public class Anagrams {
    static boolean isAnagram(String a, String b) {
        return sortStringChars(a).equals(sortStringChars(b));
    }

    static String sortStringChars(String str) {
        return str.toLowerCase().chars()
            .mapToObj(c -> (char) c)
            .sorted()
            .reduce("", (s,c) -> s.concat(String.valueOf(c)), String::concat);
    }

    public static void main(String[] args) {
        String a = "anagram";
        String b = "margana";

        boolean ret = isAnagram(a, b);
        System.out.println( (ret) ? "Yes, Anagrams!" : "Not Anagrams" );
    }
}

No comments:

Post a Comment