Home > Enterprise >  Java Collections-the number of words without repetition
Java Collections-the number of words without repetition

Time:01-23

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

CodePudding user response:

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.

CodePudding user response:

You can use a set to keep track of all the unique elements present in your string after you separate it using the delimiter "," In your example, you are keeping cat and Cat as same ( ignoring case ) . Thus, you can use this logic.

public class WordsCounter {
    public static void main(String[] args) {
        int count = uniqueWordsCounter("cat,dog,Cat,Bird,monkey");
        System.out.println(count);
    }

    public static int uniqueWordsCounter(String text) {

        String str[] = text.split(",");
        Set<String> set = new HashSet<>() ; 
        for( String temp : str)
        {
            if ( !set.contains(temp.toLowerCase()))
            {
                set.add(temp);
            }
        }
        return set.size(); 
    }
}

and the output is

4
  •  Tags:  
  • Related