Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I iterate a Java collection to get a subset, or should I convert it to array first then iterate to get it?

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 toArray() call mainly will iterate through the collection once. If that's true, then the solution one would be better?

Solution 1 -

public static List<String> get(UUID recordid, int start, int count) {
    List<String> names = new ArrayList<String>();

    ...

    Collection<String> columnnames = result.getColumnNames();
    int index = 0; 
    for (UUID columnname : columnnames) {
        if ((index >= start) && (index - start < count)) {
            names.add(columnname);
        }
        index++;
    }

    return names;
}

Solution 2 -

public static List<String> get(UUID recordid, int start, int count) {
    List<String> names = new ArrayList<String>();

    ...

    Collection<String> columnnames = result.getColumnNames();
    String[] nameArray = columnnames.toArray(new String(columnnames.size()));

    for (int index = 0; index < nameArray.length && count > 0; index++, count--) {
        names.add(nameArray[index]);
    }

    return names;
}
like image 837
tom Avatar asked Apr 05 '12 16:04

tom


2 Answers

If your Collection is a List, you can use the subList(fromIndex, toIndex) method.

Example:

List<String> x = new ArrayList<String>();
List<String> y = x.subList(5, 10);
like image 179
SWoeste Avatar answered Sep 28 '22 10:09

SWoeste


Definitely, iterating through a collection is better than converting it an array first, and then iterating through the array.

The second approach provides with extra time and memory expenses:

  1. Allocation memory for an array
  2. Filling the array with contents of the collection
like image 21
Eugene Retunsky Avatar answered Sep 28 '22 10:09

Eugene Retunsky