How to find if 2 words are anagrams in Java using Lambda and Streams?

Viewed 211

I have this Java code that find if 2 words are anagrams:

public static boolean isAnagram(String word, String anagram) {
    char[] chars = word.toCharArray();
    for (char ch : chars) {
        int index = anagram.indexOf(ch);
        if (index != -1) {
            anagram = anagram.substring(0, index) + anagram.substring(index + 1, anagram.length());
        } else {
            return false;
        }
    }
    return anagram.isEmpty();
}

I want to know if I can do this implementation using Streams instead of for-loop. And how? Thank you!

1 Answers

I would use something like that:

public static boolean isAnagram(String word, String anagram) {
    PrimitiveIterator.OfInt sortedWord = word.chars().sorted().iterator();
    PrimitiveIterator.OfInt sortedAnagram = anagram.chars().sorted().iterator();
    while(sortedWord.hasNext() && sortedAnagram.hasNext()) {
        if (!sortedWord.next().equals(sortedAnagram.next())) {
            return false;
        }
    }
    return !sortedWord.hasNext() && !sortedAnagram.hasNext();
}

It uses two streams to get sorted iterators. After that you can just loop both of them and see if they are equal. If they are you have found two anagrams.

This has also much better performance, because you are creating a new string on every iteration, which takes down the performance on large strings.

Related