Document.java
package edu.odu.cs.cs350;
import java.util.HashMap;
import java.util.Map;
/**
* Represents a text document containing a collection of words.
* <p>
* Each Document tracks the frequency of each word using {@link Word} objects.
*/
public class Document {
/**
* A string containing the name of the document.
*/
private String name;
/**
* A Map containing all of the words in the document, and the number of times they've appeared.
*/
private Map<String, Word> words;
/**
* Constructs a new Document with the specified name.
*
* @param name the name of the document (usually the file name)
*/
public Document(String name) {
this.name = name;
this.words = new HashMap<>();
}
/**
* Returns the name of this document.
*
* @return the document name
*/
public String getName() {
return name;
}
/**
* Adds a word to this document with an initial count of 1
* or increments its count if the word has already been seen.
*
* @param w the word to add
*/
public void addWord(String w) {
if (w == null || w.isEmpty()) {
// Optionally log a warning for debugging
System.err.println("Warning: ignored empty or null word.");
return;
}
Word existing = words.putIfAbsent(w, new Word(w));
if (existing != null) {
existing.incrementCount();
}
}
/**
* Returns the map of words contained in this document.
*
* @return a map where keys are word strings and values are {@link Word} objects
*/
public Map<String, Word> getWords() {
return words;
}
/**
* Calculates the total number of words (sum of all word counts)
* in this document.
*
* @return the total word count
*/
public int getTotalWordCount() {
return words.values().stream().mapToInt(Word::getCount).sum();
}
}