Groovy中Map列表转Map遇重复键覆盖问题求助
Hey there! I see exactly what's going on here—let's get this sorted for you.
First, let's clear up a key point: standard Groovy (and Java) Maps don't allow duplicate keys. When you tried using collectEntries() or sum() on your list of single-entry Maps, the second xyz key was overwriting the first one, which is why you only ended up with [xyz:343372]. That's not a bug—it's how Maps work by design!
Since your goal is to preserve both values associated with the xyz key, you'll want to create a multi-value Map where the key maps to a list of values instead of a single value. Here are two straightforward ways to do that:
Method 1: Using inject() to build the multi-value Map
This approach iterates through your list and builds up the Map by appending values to a list for each key:
def inputList = [[xyz:346654], [xyz:343372]] def multiValueMap = inputList.inject([:]) { accumulator, currentMap -> // Get the only key and value from each small map def key = currentMap.keySet().first() def value = currentMap.values().first() // Append the value to the existing list (or create a new list if the key doesn't exist) accumulator[key] = (accumulator[key] ?: []) + value accumulator } println multiValueMap // Output: [xyz:[346654, 343372]]
Method 2: Using collectMany() + groupBy()
This method flattens all the entries first, groups them by key, then converts each group into a list of values:
def inputList = [[xyz:346654], [xyz:343372]] def multiValueMap = inputList.collectMany { it.entrySet() } .groupBy { it.key } .collectEntries { key, entries -> [key, entries*.value] } println multiValueMap // Output: [xyz:[346654, 343372]]
Why your original methods failed
collectEntries(): When you runinputList.collectEntries(), it processes each small Map in order. The first entry addsxyz:346654to the result, then the second entry overwrites that key with343372.sum(): Groovy'ssum()for Maps merges them, and again, duplicate keys get overwritten by the last occurrence.
If you absolutely must have a structure that keeps duplicate keys (though this is highly discouraged because it breaks standard Map behavior), you'd need to use a custom implementation like Apache Commons' MultiMap—but in most cases, the multi-value Map approach above is the cleanest, idiomatic solution for your use case.
内容的提问来源于stack exchange,提问作者smartCoder

