Open Source Consultant, Software Developer and System Administrator

If you are interrested in hiring a consultant for the effective use of open source software on an enterprise grade, take a look around in the About section to see, what I have to offer.

Blog and snippets

Various snippets or code parts I found useful, so I keep them here for reference.

TIL: collectEntries in Groovy also accepts a map input

collectEntries in Groovy works on collections: an optionally passed closure (otherwise identity is used) must return either tuples (two element arrays/lists -- think key and value) or maps and it turns that into a map. E.g.:

[[1,2],[3,4]].collectEntries()
// → [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:

[[1,2],[3,4]].collectEntries().getClass()
// → 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]