compactObject
Returns a copy of a Map with every null-valued key removed — one level deep.
Map<K, V> compactObject<K, V>(Map<K, V?> map)
Lecture
compactObject is the Map counterpart of
compact (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
compactObject again on the nested map before assembling the
outer one).
Demo 1 · Basics
Demo 2 · Proof it's shallow
Try it yourself
Exercise: use compactObject to drop the null-valued keys in draft.