I don't have a lot to say, but this is my little bit.

Sunday, November 25, 2012

Process Word List By Length

This is a "smart dictionary", which processes a word list into collections based on the length of the word.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
    
/**
 * This smart dictionary holds a list of words and also caches them by size. This is an optimization for running through a lot of words one after another.
 * @author nrrkeene
 *
 */
public class SmartDictionary {
    private List<String> words;
    private Map<Integer, List<String>> wordsByLength;
    
    public SmartDictionary(List<String> words) {
        this.words = words;
        this.wordsByLength = new HashMap<Integer, List<String>>();
        for(String word: words) {
            List<String> wordsOfLength = this.wordsByLength.get(word.length());
            if(wordsOfLength == null) wordsOfLength = new ArrayList<String>();
            wordsOfLength.add(word);
            this.wordsByLength.put(word.length(), wordsOfLength);
        }
    }
    
    public List<String> allWords() {
        return this.words;
    }
    
    public List<String> wordsByLength(int length) {
        List<String> wordsOfLength = this.wordsByLength.get(length);
        if(wordsOfLength == null) wordsOfLength = new ArrayList<String>();
        return wordsOfLength;
    }
    
}

No comments:

Post a Comment