You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Groovy中Map列表转Map遇重复键覆盖问题求助

Fixing Your Groovy List-to-Map Conversion Issue

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 run inputList.collectEntries(), it processes each small Map in order. The first entry adds xyz:346654 to the result, then the second entry overwrites that key with 343372.
  • sum(): Groovy's sum() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:18:06