我有invoiceList
如下所示,这是 List<Map<String:String>>
我试图查明所有发票是否都相同 SENDER_COUNTRY
和CLIENT_COUNTRY
是否,如果不是,它会将消息添加到 JSON 数组
[
[INVOICE_DATE:20150617, INVOICE_NUMBER:617151,SENDER_COUNTRY:USA, CLIENT_COUNTRY:USA]
[INVOICE_DATE:20150617, INVOICE_NUMBER:617152,SENDER_COUNTRY:CAD, CLIENT_COUNTRY:MEX]
[INVOICE_DATE:20150617, INVOICE_NUMBER:617153,SENDER_COUNTRY:CAD, CLIENT_COUNTRY:MEX]
]
JSONArray jsonArray = new JSONArray();
def senderCountry = invoiceList[0]['SENDER_COUNTRY']
def clientCountry = invoiceList[0]['CLIENT_COUNTRY']
invoiceList.each{ it ->
if(it['SENDER_COUNTRY'] != senderCountry)
jsonArray.add((new JSONObject()).put("SENDER_COUNTRY","Multiple sender Countries Associated"));
if(it['CLIENT_COUNTRY'] != clientCountry)
jsonArray.add((new JSONObject()).put("CLIENT_COUNTRY","Multiple Client Countries Associated"));
}
我觉得这段代码可以在 Groovy 中重构/优化为更好的版本,有人可以帮我吗?
最佳答案
这个怎么样(请注意,我的答案不会提高性能):
def invoiceList = [
[INVOICE_DATE:20150617, INVOICE_NUMBER:617151,SENDER_COUNTRY:'USA', CLIENT_COUNTRY:'USA'],
[INVOICE_DATE:20150617, INVOICE_NUMBER:617152,SENDER_COUNTRY:'CAD', CLIENT_COUNTRY:'MEX'],
[INVOICE_DATE:20150617, INVOICE_NUMBER:617153,SENDER_COUNTRY:'CAD', CLIENT_COUNTRY:'MEX']
]
def jsonarray = []
if (invoiceList.countBy{ it.CLIENT_COUNTRY }.size > 1)
jsonarray << [CLIENT_COUNTRY: "Multiple client countries associated"]
if (invoiceList.countBy{ it.SENDER_COUNTRY }.size > 1)
jsonarray << [SENDER_COUNTRY: "Multiple sender countries associated"]
groovy.json.JsonOutput.toJson(jsonarray)
// Result: [{"CLIENT_COUNTRY":"Multiple client countries associated"},{"SENDER_COUNTRY":"Multiple sender countries associated"}]
关于performance - Groovy:优化代码以查找重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43881683/