See How to convert List<Integer> to int[] in Java? (which is a duplicate by all means; see this answer in particular).
However, for sake of discussion, consider this similar alternative and notes.
List<Integer> filters = getFilters();
// Arrays must be created with a size: the original code won't compile.
int[] ints = new int[filters.size()];
// Use an Enhanced For Loop if an index lookup into the source
// is not required; i is merely a result of needing to index the target.
int i = 0;
for(Integer filter : filters) {
// Just use auto unboxing Integer->int; no need for intValue()
ints[i++] = filter;
}
The original code is terrible because filters.toArray(new Integer[filters.size()])[i]
creates a new array from the list each loop before the index operation. This makes the complexity O(n^2)+ just for the copy! While this can be fixed by replacing the offending expression with filters.get(i)
, an indexing operation can be skipped entirely in this case.
Using an enumerable approach similar to shown above (i.e. with an enhanced for loop) has the advantage that it will continue to work efficiently over source collections which are not fast-indexable such as a LinkedList. (Even using the filters.get(i)
replacement, a LinkedList source collection would result in a O(n^2) complexity for the transformation - yikes!)