TIL: collectEntries in Groovy can also work with a map as input

collectEntries is valuable function, that Groovy adds to collections. It works on collections and an optionally passed closure (otherwise identity is used) must return either tuples (two element arrays/lists) or maps and it turns that into a map itself. E.g.:

// → [1:2, 3:4]
[[a: 1, b: 2],[c: 3]].collectEntries()
// → [a:1, b:2, c:3]
[1,2,3].collectEntries{ [it, it] }
// → [1:1, 2:2, 3:3]

So this creates maps. But what map exactly? Educated guess: LinkedHashMap, which is also the implementation the Groovy map literal uses. Let's check:

// → class java.util.LinkedHashMap

So what if we want another data structure? A not so well know feature (at least to me), is the possibility to pass in an existing map.

So this can be used to pick an appropriate data type:

[3,2,1].collectEntries(new TreeMap()){ [it, it] }
// → [1:1, 2:2, 3:3]

Or to append to an existing map:

[1,2,3].collectEntries([(0): 0]){ [it, it] }
// → [0:0, 1:1, 2:2, 3:3]