Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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);
}
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading