Axel
Axel

Reputation: 23

Count amount of unique words from a text file

I have a 40 000 ish text file. All the words from the text file are saved in an ArrayList.

I want to find how many unique words there are in that file and return that value to the main class. So if there is a unique word the counter goes up by one.

I would like the output to be

   Amount of unique words: 7000

I tried

       public int antallOrd() {
          Set<Ord> unik = new HashSet<Ord>(ordListe) ;
            for (Ord unikt : unik) {
            System.out.println(nokkel + ": " + Collections.frequency(ordListe, nokkel));
       }

but didnt quite understand how to implement a counter to this

thanks in advance

Upvotes: 1

Views: 168

Answers (2)

Sammy
Sammy

Reputation: 477

Put the words into a java.util.Bag and print the size() of the bag.

You could also use Hashtable keyed on the word if you wanted to keep a count of each word.

Upvotes: 0

arcy
arcy

Reputation: 13123

You don't have to iterate through unik - it is a set, and putting all the words in that set removed the duplicates. The size of unik is the answer to your question.

Upvotes: 4

Related Questions