Implement isAnagram(String word1, String word2) that returns true if word1 is an anagram of word2 and returns false word1 is’n an anagram of word2.

For example isAnagram(“word”, “drow”) returns true, isAnagram(“word”, “draw”) returns false.

Empty strings are not anagrams

Solution in Java

We’re going to sort characters of strings and compare

    public boolean isAnagram(String word1, String word2) {
        if (word1 == null || word2 == null || word1) return false;
        return stringToSortedList(word1).equals(stringToSortedList(word2));
    }

    public List<Integer> stringToSortedList(String word) {
        return word.chars().sorted().boxed().collect(Collectors.toList());
    }

Some tests

    @Test
    public void anagramTest() {
        Assert.assertTrue(isAnagram("word", "drow"));
    }

    @Test
    public void firstWordIsNullTest() {
        Assert.assertFalse(isAnagram(null, "drow"));
    }

    @Test
    public void secondWordIsNullTest() {
        Assert.assertFalse(isAnagram("word", null));
    }

    @Test
    public void emptyWordsTest() {
        Assert.assertFalse(isAnagram("", ""));
    }

    @Test
    public void notAnagramTest() {
        Assert.assertFalse(isAnagram("word", "draw"));
    }