How to flatten a map in Groovy

Flatten usually means merge all elements of collections within collections regardless of their level into a flat collection.

Example:

assert [ [1,2], 3, [[4], [5]] ].flatten() == [1,2,3,4,5]

There is is keywork to flatten map in groovy.

Example:

assert [a:[b:1, c:[d:1,e:1]]].flatten() == ['a.b':1, 'a.c.d':1, 'a.c.e':1]

Here is a function which does that:

Map flatten(Map m, String separator = '.') { m.collectEntries { k, v ->  v instanceof Map ? flatten(v, separator).collectEntries { q, r ->  [(k + separator + q): r] } : [(k):v] } }

assert flatten([a:1]) == [a:1]
assert flatten([a:1, b:1]) == [a:1, b:1]
assert flatten([a:[b:1, c:1]]) == ['a.b':1, 'a.c':1]
assert flatten([a:[b:1, c:[d:1,e:1]]]) == ['a.b':1, 'a.c.d':1, 'a.c.e':1]
assert flatten([a:[b:1, c:[d:1,e:1]]], ' and ') == ['a and b':1, 'a and c and d':1, 'a and c and e':1]