Java Collections-the number of words without repetition

Solution 1:

One way is to use the distinct() operation from the stream API:

import java.util.*;

public class WordsCounter {
    public static void main(String[] args) {
        uniqueWordsCounter("cat, dog, Cat, Bird, monkey");
    }

    public static void uniqueWordsCounter(String text) {
        String[] words = text.toLowerCase().split(",\\s*");
        List<String> wordsList = Arrays.asList(words);
        System.out.println(wordsList);
        System.out.println("Count of distinct elements: "
                           + wordsList.stream().distinct().count());
    }
}

Example run:

$ java Demo.java
[cat, dog, cat, bird, monkey]
Count of distinct elements: 4

Note splitting on comma followed by optional whitespace instead of your replacing commas and then splitting, to help simplify things.