title: Counting occurrences of words in an array
body: <p>I've been working on something which takes a stream of characters, forms words, makes an array of the words, then creates a vector which contains each unique words and the number of times it occurs (basically a word counter).</p>
  
  <p>Anyway I've not used Java in a long time, or much programming to be honest and I'm not happy with how this currently looks.  The part I have which makes the vector looks ugly to me and I wanted to know if I could make it less messy.</p>
  
  <pre><code>    int counter = 1;
      Vector&lt;Pair&lt;String, Integer&gt;&gt; finalList = new Vector&lt;Pair&lt;String, Integer&gt;&gt;();
      Pair&lt;String, Integer&gt; wordAndCount = new Pair&lt;String, Integer&gt;(wordList.get(1), counter); // wordList contains " " as first word, starting at wordList.get(1) skips it.
  
      for(int i= 1; i&lt;wordList.size();i++){
          if(wordAndCount.getLeft().equals(wordList.get(i))){
              wordAndCount = new Pair&lt;String, Integer&gt;(wordList.get(i), counter++);
          }
          else if(!wordAndCount.getLeft().equals(wordList.get(i))){
              finalList.add(wordAndCount);
              wordAndCount = new Pair&lt;String, Integer&gt;(wordList.get(i), counter=1);
          }
      }
      finalList.add(wordAndCount); //UGLY!!
  </code></pre>
  
  <p>As a secondary question, this gives me a vector with all the words in alphabetical order (as in the array).  I want to have it sorted by occurrence, the alphabetical within that.</p>
  
  <p>Would the best option be:</p>
  
  <ul>
  <li><p>Iterate down the vector, testing each occurrence int with the one above, using <code>Collections.swap()</code> if it was higher, then checking the next one above (as its now moved up 1) and so on until it's no longer larger than anything above it.  Any occurrence of 1 could be skipped.</p></li>
  <li><p>Iterate down the vector again, testing each element against the first element of the vector and then iterating downwards until the number of occurrences is lower and inserting it above that element.  All occurrences of 1 would once again be skipped.</p></li>
  </ul>
  
  <p>The first method would doing more in terms of iterating over the elements, but the second one requires you to add and remove components of the vector (I think?) so I don't know which is more efficient, or whether its worth considering.</p>