SparseArray
Iteration
Programming
Data Structures
Algorithms

How to iterate through SparseArray?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

On Android, SparseArray is a compact mapping from int keys to object values. To iterate through it, you loop over internal indices from 0 to size() - 1, then read the stored key with keyAt(index) and the stored value with valueAt(index).

Understand the Difference Between Keys and Indices

The most important detail is that a SparseArray is not a dense array. The keys may be 3, 10, and 1000, but the stored entries still sit at internal positions 0, 1, and 2.

That is why iteration uses the container size, not the numeric key range.

java
1SparseArray<String> users = new SparseArray<>();
2users.put(100, "Ava");
3users.put(200, "Liam");
4users.put(500, "Mina");
5
6for (int index = 0; index < users.size(); index++) {
7    int key = users.keyAt(index);
8    String value = users.valueAt(index);
9    System.out.println(key + " -> " + value);
10}

This is the standard pattern and the one you should memorize.

Why Scanning Every Possible Key Is Wrong

A common mistake is looping from 0 to the maximum key and calling get for each integer.

java
1for (int key = 0; key <= 500; key++) {
2    String value = users.get(key);
3    if (value != null) {
4        System.out.println(value);
5    }
6}

That approach is inefficient because most keys do not exist. It also misses the point of a sparse structure, which is optimized for stored entries rather than dense numeric ranges.

Reading Keys and Values Safely

The accessors you will use most are:

  • 'size() for how many entries exist'
  • 'keyAt(index) for the stored key at a position'
  • 'valueAt(index) for the stored value at a position'
  • 'get(key) when you already know the key'

You can also locate a key or a value by index-based search if needed.

java
1int position = users.indexOfKey(200);
2if (position >= 0) {
3    System.out.println(users.valueAt(position));
4}

This is useful when you receive a key from elsewhere and need to inspect where it sits in the structure.

Updating Values While Iterating

If you need to modify values in place, iterate by index and use setValueAt or put.

java
1SparseArray<Integer> scores = new SparseArray<>();
2scores.put(1, 10);
3scores.put(2, 20);
4
5for (int index = 0; index < scores.size(); index++) {
6    int current = scores.valueAt(index);
7    scores.setValueAt(index, current + 5);
8}
9
10for (int index = 0; index < scores.size(); index++) {
11    System.out.println(scores.keyAt(index) + " -> " + scores.valueAt(index));
12}

If you change the structure itself while iterating, think carefully about index shifts. Updating a value is usually fine. Removing entries mid-loop can invalidate later positions.

Kotlin Version

The same logic applies in Kotlin. Only the syntax changes.

kotlin
1val users = SparseArray<String>()
2users.put(100, "Ava")
3users.put(200, "Liam")
4users.put(500, "Mina")
5
6for (index in 0 until users.size()) {
7    val key = users.keyAt(index)
8    val value = users.valueAt(index)
9    println("$key -> $value")
10}

A Kotlin extension function can make this even cleaner if your project uses SparseArray heavily, but the underlying mechanism remains index-based.

Android includes several related classes with the same iteration model:

  • 'SparseIntArray'
  • 'SparseBooleanArray'
  • 'SparseLongArray'
  • 'LongSparseArray'

For example:

java
1SparseIntArray counts = new SparseIntArray();
2counts.put(7, 3);
3counts.put(42, 9);
4
5for (int index = 0; index < counts.size(); index++) {
6    int key = counts.keyAt(index);
7    int value = counts.valueAt(index);
8    System.out.println(key + " -> " + value);
9}

Once you understand SparseArray, the rest of the family behaves predictably.

Common Pitfalls

The biggest pitfall is confusing the sparse key with the iteration index. Another is scanning every possible integer key instead of iterating stored entries.

Removing items while iterating can also cause skipped or repeated positions if you do not adjust the loop. Finally, avoid assuming order based on insertion alone; read keys explicitly if ordering matters to your logic.

Summary

  • Iterate SparseArray by internal index from 0 to size() - 1.
  • Use keyAt(index) and valueAt(index) to access stored entries.
  • Do not loop across the full numeric key range for sparse data.
  • Update values carefully and be cautious about structural changes during iteration.
  • The same pattern applies to other Android sparse collections.

Course illustration
Course illustration

All Rights Reserved.