Groovy迭代和更新Map <string,list <string>&gt;值</串,列表<字符串>

时间:2015-04-06 21:07:55

标签: collections groovy iteration

我有一个Map<String,List<String>> invoiceErrorLines,如下所示

invoiceErrorLines = ['1660277':['Line : 1 Invoice does not foot Reported', 'Line : 1 MATH ERROR'], 
                '1660278':['Line : 5 Invoice does not foot Reported'], 
                '1660279':['Line : 7 Invoice does not foot Reported'], 
                '1660280':['Line : 9 Invoice does not foot Reported']]

迭代地图并更改错误消息的行号,如下所示,但是在打印invoiceErrorLines地图时没有看到更新的错误消息

invoiceErrorLines.each{ invNum ->
   invNum.value.each{
      int actualLineNumber = getActualLineNumber(it)
      it.replaceFirst("\\d+", String.valueOf(actualLineNumber))
   }  
}

有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:2)

您只是迭代字符串并在其上调用replaceFirst。这不会改变您的数据。您更愿意collect您的数据。 E.g:

invoiceErrorLines = [
    '1660277':['Line : 1 Invoice does not foot Reported', 'Line : 1 MATH ERROR'], 
    '1660278':['Line : 5 Invoice does not foot Reported'], 
    '1660279':['Line : 7 Invoice does not foot Reported'], 
    '1660280':['Line : 9 Invoice does not foot Reported']
]

println invoiceErrorLines.collectEntries{ k,v -> 
    [k, v.collect{ it.replaceFirst(/\d+/, '1') }] 
}

// Results: =>
[
    1660277: [Line : 1 Invoice does not foot Reported, Line : 1 MATH ERROR], 
    1660278: [Line : 1 Invoice does not foot Reported], 
    1660279: [Line : 1 Invoice does not foot Reported],
    1660280: [Line : 1 Invoice does not foot Reported]
]