Is there a way to iterate over Java SparseArray (for Android) ? I used sparsearray
to easily get values by index. I could not find one.
There is no way to iterate over a set without an iterator, apart from accessing the underlying structure that holds the data through reflection, and replicating the code provided by Set#iterator...
The best way to iterate the list in terms of performance would be to use iterators ( your second approach using foreach ).
Since integers, individualistically, are not iterable, when we try to do a for x in 7 , it raises an exception stating TypeError: 'int' object is not iterable .
forEach() method is available in Java 8 and each collection has this method that implements the iteration internally. Syntax used : With iterable variable.
Seems I found the solution. I hadn't properly noticed the keyAt(index)
function.
So I'll go with something like this:
for(int i = 0; i < sparseArray.size(); i++) { int key = sparseArray.keyAt(i); // get the object by the key. Object obj = sparseArray.get(key); }
If you don't care about the keys, then valueAt(int)
can be used to while iterating through the sparse array to access the values directly.
for(int i = 0, nsize = sparseArray.size(); i < nsize; i++) { Object obj = sparseArray.valueAt(i); }
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