title: Should I iterate a Java collection to get a subset, or should I convert it to array first then iterate to get it?
body: <p>I am calling an API which returns me a collection of objects. I want to get a subset of the objects. There are two solutions that I am thinking. Which one would give me better performance? Based on my understanding, the <code>toArray()</code> call mainly will iterate through the collection once. If that's true, then the solution one would be better? </p>
  
  <p>Solution 1 -</p>
  
  <pre><code>public static List&lt;String&gt; get(UUID recordid, int start, int count) {
      List&lt;String&gt; names = new ArrayList&lt;String&gt;();
  
      ...
  
      Collection&lt;String&gt; columnnames = result.getColumnNames();
      int index = 0; 
      for (UUID columnname : columnnames) {
          if ((index &gt;= start) &amp;&amp; (index - start &lt; count)) {
              names.add(columnname);
          }
          index++;
      }
  
      return names;
  }
  </code></pre>
  
  <p>Solution 2 -</p>
  
  <pre><code>public static List&lt;String&gt; get(UUID recordid, int start, int count) {
      List&lt;String&gt; names = new ArrayList&lt;String&gt;();
  
      ...
  
      Collection&lt;String&gt; columnnames = result.getColumnNames();
      String[] nameArray = columnnames.toArray(new String(columnnames.size()));
  
      for (int index = 0; index &lt; nameArray.length &amp;&amp; count &gt; 0; index++, count--) {
          names.add(nameArray[index]);
      }
  
      return names;
  }
  </code></pre>