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

基于值拆分Map为两个Map(Groovy/Java实现)

解决方案验证与优化

你提供的Groovy代码正确性确认

这段代码是可行且正确的:

  • 使用Iterator遍历mapA的entrySet,避免了直接遍历修改集合时的ConcurrentModificationException
  • 筛选出值列表第2个元素(索引1)为"InComplete"的键值对,放入mapB
  • 通过iterator.remove()同步从原mapA中移除对应元素,最终mapA仅保留含"Complete"的条目,mapB存储所有"InComplete"条目

小优化:mapB不需要withDefault,直接用空Map初始化即可,因为你是直接put已有的entry,不会触发默认值逻辑:

def mapB = [:]
Iterator<Map.Entry<Object, ArrayList>> iterator = mapA.entrySet().iterator()
while (iterator.hasNext()) {
    Map.Entry<Object, ArrayList> entry = iterator.next()
    if (entry.getValue()[1] == "InComplete") { // Groovy支持直接用下标访问列表
        mapB[entry.key] = entry.value
        iterator.remove()
    }
}

更简洁的Groovy实现方案

如果不想修改原mapA,而是生成两个独立的新Map,用Groovy的findAll可以一行搞定:

// 生成仅含Complete的新Map
def mapAComplete = mapA.findAll { it.value[1] == "Complete" }
// 生成仅含InComplete的新MapB
def mapBInComplete = mapA.findAll { it.value[1] == "InComplete" }

这种方式完全不改动原mapA,代码更简洁,符合Groovy的语法风格。

关于Java8代码的补充

你提供的Java8代码只能生成新Map,无法修改原mapA。如果要在Java8中同时修改原Map,需要额外执行移除操作:

// 先收集要移除的key
List<Object> keysToRemove = mapA.entrySet().stream()
    .filter(entry -> entry.getValue().get(1).equals("InComplete"))
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());
// 从原Map中移除
keysToRemove.forEach(mapA::remove);
// 生成MapB
Map<Object, ArrayList> mapB = mapA.entrySet().stream()
    .filter(entry -> entry.getValue().get(1).equals("InComplete"))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

但显然Groovy的实现更简洁高效。

内容的提问来源于stack exchange,提问作者deewreck

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 00:41:03