Search code examples
javastringcollectionsequalscompareto

Java Collections-the number of words without repetition


I wan to create a method for which we give text(String) as an input argument. The method will return the number of words without repetition. For example: "cat, dog, Cat, Bird, monkey" return value:4

How can I compare each Collections item with each other? What I already have:

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

public static void uniqueWordsCounter(String text) {

    String processedText = text.toLowerCase().replaceAll(",", "");
    String[] words = processedText.split("\\s");
    List<String> wordsList = Arrays.asList(words);
}
}

Solution

  • 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.