title: Getting the first (and only value) from a collection
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/1671378/java-get-first-item-from-a-collection">Java: Get first item from a collection</a>  </p>
  </blockquote>
  
  
  
  <p>In Java, I often encounter a collection with one single element, which I need to retrieve. Because collections do not guarantee consistent ordering, there is no <code>first()</code> or <code>get(int index)</code> methods, so I need to use rather ugly things, such as:</p>
  
  <pre><code>public Integer sillyExample(Collection&lt;Integer&gt; collection){
      if(collection.size()==1){
          return collection.iterator().next();
      }
      return someCodeToDecideBetweenElements(collection);
  }
  </code></pre>
  
  <p>So, how do <em>you</em> get the only element out? I can't believe there isn't a better way...</p>
  
  <p>Please note, I understand there's no concept of "first", I'm just trying to avoid building an iterator when I know there is only one element in it.</p>
  
  <p>EDIT: Peter Wooster found a very similar question <a href="https://stackoverflow.com/questions/1671378/java-get-first-item-from-a-collection">here</a>. I'm leaving this open because I'm not trying to get the "first" element, which would imply a consistent ordering, but the "one and only" element after checking that it indeed is the only element.</p>