LruCache

class LruCache<K, V>(val maxSize: Int)

A fixed-capacity cache that evicts the least recently used entry first.

get, getOrPut on a hit, and put mark the entry most recently used; containsKey, keys, and toMap do not affect recency. When put inserts a new key while the cache already holds maxSize entries, the least recently used entry is evicted before the insert. All operations run in amortized constant time. Backed by LinkedHashMap.

This class is not thread-safe.

Type Parameters

K

the key type.

V

the value type.

Throws

Constructors

Link copied to clipboard
constructor(maxSize: Int)

Creates an empty cache that holds at most maxSize entries.

Properties

Link copied to clipboard

The maximum number of entries the cache holds. Always positive.

Link copied to clipboard
val size: Int

The number of entries currently in the cache, from 0 to maxSize.

Functions

Link copied to clipboard
fun clear()

Removes every entry from the cache.

Link copied to clipboard
fun containsKey(key: K): Boolean

Returns true if key has an entry in the cache. Does not affect recency.

Link copied to clipboard
fun get(key: K): V?

Returns the value for key and marks it most recently used, or returns null if the key is absent.

Link copied to clipboard
fun getOrPut(key: K, defaultValue: () -> V): V

Returns the value for key if present, otherwise computes it with defaultValue, stores it, and returns it.

Link copied to clipboard
fun keys(): Set<K>

Returns a snapshot of the keys in eviction order, least recently used first. Does not affect recency.

Link copied to clipboard
fun put(key: K, value: V): V?

Stores value under key and marks the entry most recently used.

Link copied to clipboard
fun remove(key: K): V?

Removes the entry for key and returns its value, or returns null if the key is absent.

Link copied to clipboard
fun toMap(): Map<K, V>

Returns a snapshot of the entries in eviction order, least recently used first. Does not affect recency.