001package de.hdm_stuttgart.mi.sd1.textstat;
002
003import java.util.Comparator;
004
005/**
006 * A helper class to account for frequencies of words found in textual input. 
007 *
008 */
009public class WordFrequency {
010  /**
011   * The frequency of this word will be counted.
012   */
013  public final String word;
014  private int frequency;
015  
016  /**
017   * @param word The immutable value. Has to be non-null.
018   */
019  public  WordFrequency(final String word) {
020    this.word = word;
021    frequency = 1;
022  }
023  
024  /**
025   * We found another one. Thus increment the total number
026   * to be returned by {@link #getFrequency()}.
027   */
028  public void incrementFrequency() {
029    frequency++;
030  }
031  /**
032   * @return The number of appearances so far.
033   */
034  public int getFrequency() {
035    return frequency;
036  }
037
038  @Override
039  public int hashCode() {
040    return word.hashCode();
041  }
042
043  @Override
044  public boolean equals(Object obj) {
045    if (obj instanceof WordFrequency) {               // WordFrequency instances are equal if and
046      return ((WordFrequency) obj).word.equals(word); // only if the underlying words are equals
047    } else {
048      return false;
049    }
050  }
051  /**
052   * Compare by word frequencies
053   *
054   */
055  public static class CompareByFrequency implements Comparator<WordFrequency> {
056
057    @Override
058    public int compare(WordFrequency wf1, WordFrequency wf2) {
059      final int frequencyDifference = wf2.frequency - wf1.frequency;
060      if (0 == frequencyDifference) { // Frequencies are equal, thus sort alphabetically
061        return wf1.word.compareTo(wf2.word);
062      } else {
063        return frequencyDifference;
064      }
065    }
066  }
067}