fxCompactObject

Returns a copy of a Map with every null-valued key removed — one level deep.

Map<K, V> fxCompactObject<K, V>(Map<K, V?> map)

Lecture

fxCompactObject is the Map counterpart of fxCompact (which strips nulls out of an Iterable). It's handy for cleaning up a form or a partially-filled record before serializing it — drop the fields nobody filled in, keep everything else.

The cleanup is shallow: it only inspects the top-level values. A null nested two levels down, inside a value that's itself a Map, is left completely alone. If you need a recursive clean, you'd write that pass yourself (or call fxCompactObject again on the nested map before assembling the outer one).

Demo 1 · Basics

Demo 2 · Proof it's shallow

Try it yourself

Exercise: use fxCompactObject to drop the null-valued keys in draft.

Related: fxCompact — the Iterable version · isEmpty — a related value-based check · fxOmitBy — the general predicate version this specializes · fxEvolve — transform values instead of dropping them