title: Removing the "first" object from a Set
body: <p>Under certain situations, I need to evict the oldest element in a Java <code>Set</code>. The set is implemented using a <a href="http://download.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html" rel="noreferrer"><code>LinkedHashSet</code></a>, which makes this simple: just get rid of the first element returned by the set's iterator:</p>
  
  <pre><code>Set&lt;Foo&gt; mySet = new LinkedHashSet&lt;Foo&gt;();
  // do stuff...
  if (mySet.size() &gt;= MAX_SET_SIZE)
  {
      Iterator&lt;Foo&gt; iter = mySet.iterator();
      iter.next();
      iter.remove();
  }
  </code></pre>
  
  <p>This is ugly: 3 lines to do something I <em>could</em> do with 1 line if I was using a <code>SortedSet</code> (for other reasons, a <code>SortedSet</code> is not an option here):</p>
  
  <pre><code>if (/*stuff*/)
  {
      mySet.remove(mySet.first());
  }
  </code></pre>
  
  <p>So is there a cleaner way of doing this, <strong>without:</strong></p>
  
  <ul>
  <li>changing the <code>Set</code> implementation, or</li>
  <li>writing a static utility method?</li>
  </ul>
  
  <p>Any solutions leveraging <a href="http://code.google.com/p/guava-libraries/" rel="noreferrer">Guava</a> are fine.</p>
  
  <hr>
  
  <p><sub>I am fully aware that sets do not have inherent ordering. I'm asking about removing the first entry as defined by iteration order.</sub></p>