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;
}
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);
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With