Back to results for “Collections Framework”
Java › Arrays & Multidimensional Arrays

How would you implement a memory-efficient sparse matrix representation in Java when a large 2D array would mostly contain zero/default values, avoiding the memory waste of a full dense array?

Advanced

Answer

A sparse matrix stores only the non-default (non-zero) elements, commonly using a Map<Long, T> keyed by an encoded (row, column) pair, or a Map<Integer, Map<Integer, T>> for nested row-then-column lookup, or specialized formats like Compressed Sparse Row (CSR) for numerical computing -- this avoids allocating and holding memory for the potentially enormous number of default-valued cells a genuinely sparse dataset (like a large graph's adjacency matrix, or a mostly-empty spreadsheet) would otherwise require if represented as a dense 2D array.
public class SparseMatrix {
    private final Map<Long, Double> data = new HashMap<>();
    private final int cols;
    public SparseMatrix(int cols) { this.cols = cols; }

    private long key(int row, int col) { return (long) row * cols + col; }

    public void set(int row, int col, double value) {
        if (value == 0.0) data.remove(key(row, col));
        else data.put(key(row, col), value);
    }

    public double get(int row, int col) {
        return data.getOrDefault(key(row, col), 0.0);
    }
}
Real-world example A recommendation engine's user-item interaction matrix (millions of users by millions of items, but each user has only interacted with a tiny fraction) is stored as a sparse Map-based structure rather than a dense 2D array, since a dense representation at that scale would require far more memory than any reasonable server could provide.

Common follow-ups: What's the performance trade-off of Map-based sparse storage versus a dense array for operations like matrix multiplication?;How do specialized sparse matrix libraries (like those used in scientific computing) further optimize beyond a simple HashMap-based approach?