Sorting all words in a file by length, in one read. (Java)
<p>The assignment, for my data structures class, is to find the shortest path from one word to another. </p>

<p>i.e. Start: bleed -> blend -> blond -> End: blood, with a cost of 3.</p>

<p>I'm given a list of words that I have to group using a map. Where:</p>

<p>Key: length of word, Value: Set of all words with that length.</p>

<p>I already finished the program but I think I can improve performance if I change the way I store the sets in the map. Right now I do a scan through the text file and store each individual word into an ArrayList, then I go through the ArrayList and store all words of length x into a set while removing each word from the List. I continue like that starting from the first element in the ArrayList until the List is empty.</p>

<p>I was wondering it if I could do this sorting as I'm reading in the file, and avoid the ArrayList altogether.</p>

<p>This is the code I have:</p>

<pre><code>ArrayList&lt;String&gt; wordList = new ArrayList&lt;String&gt;();
Map&lt;Integer, Set&gt; setMap = new HashMap&lt;Integer, Set&gt;();
Graph pathGraph = new Graph();

private void readFile(String file) {
    try {
        FileReader f = new FileReader(file);
        BufferedReader reader = new BufferedReader(f);
        String line = "";
        while ((line = reader.readLine()) != null) {
            wordList.add(line);
        }

    } catch (Exception e) { //Done in case of an exception
        System.out.println("No file found.");
    }
}

private void mapMaker() {
    int wordLength = 1;
    Set&lt;String&gt; wordSet = new HashSet&lt;String&gt;();
    while (!wordList.isEmpty()) {
        wordSet = setBuilder(wordLength);
        if (!wordSet.isEmpty()) {
            setMap.put(wordLength, wordSet);
        }
        wordLength++;
    }
}

private Set&lt;String&gt; setBuilder(int x) {
    Set&lt;String&gt; wordSet = new HashSet&lt;String&gt;();
    int counter = 0;
    while (counter &lt; wordList.size()) {
        if (wordList.get(counter).length() == x) {
            wordSet.add(wordList.get(counter));
            wordList.remove(counter);
        } else {
            counter++;
        }
    }
    return wordSet;
}
</code></pre>

<p>Thanks, in advance for any input.</p>
