如何组合2个没有重复的对象列表?

时间:2017-03-02 14:26:42

标签: groovy

我有2个groovy sql结果集,我需要组合结果集,以便project_no应该是唯一的,case_no可以有多个元素,如果有重复project_no

下面是2个groovy sql结果集

[[project_no:0-10001,case_no:00492268],[project_no:0-10160,case_no:01957580],[project_no:1-10014,case_no:02022686]]

[[project_no:0-10160,case_no:01957590],[project_no:1-10014,case_no:019126],[project_no:1-2896337,case_no:02039596]]

所需清单

[[project_no:0-10001,case_nos:[00492268]], [project_no:0-10160,case_nos:[01957580,01957590]] ,[project_no:1-10014,case_nos:[02022686,019126]], [project_no:1-2896337,case_nos:[02039596]]]

这就是我试过的

caseResultForAnalysis.each { ca ->
    def ptmp = [:], caseList = []
    tempPrList.add(ca["project_no"])
    ptmp["project_no"] = ca["project_no"]
    caseList.add(ca["case_no"])
    if (caseList.size() > 0) {
        ptmp["case_nos"] = caseList
        mergedCaseResult.push(ptmp)
    }
}
mergedCaseResult.each { ma ->
    def ptmp = [:], caseList = []
    caseResultForUploads.each { cp ->
        if (!tempPrList.contains(cp["project_no"])) {
            ptmp["project_no"] = ma["project_no"]
            caseList.add(cp["case_no"])
        } else if (ma["project_no"] == cp["project_no"]) {
            //if (!ma["case_nos"].contains(cp["case_no"]))
            List tmp = ma["case_nos"]
            if (!tmp.contains(cp["case_no"]))
                ma["case_nos"].add(cp["case_no"])
        }
    }
    if (caseList.size() > 0) {
        ptmp["case_nos"] = caseList
        mergedCaseResult.push(ptmp)
    }
}

//1st list caseResultForAnalysis
//2nd List caseResultForUploads
//desired List mergedCaseResult

2 个答案:

答案 0 :(得分:2)

你可以多做一点" groovy"用:

def list1 = [[project_no:'0-10001',case_no:'00492268'],[project_no:'0-10160',case_no:'01957580'],[project_no:'1-10014',case_no:'02022686']]
def list2 = [[project_no:'0-10160',case_no:'01957590'],[project_no:'1-10014',case_no:'019126'],[project_no:'1-2896337',case_no:'02039596']]

def finalResult = (list1 + list2).groupBy { it.project_no }
                                 .collect { k, v -> [project_no:k, case_no:v.case_no.unique()] }

答案 1 :(得分:1)

我确信这可以更加彻底改变。

这是执行OP所需的脚本。

def list1 = [[project_no:'0-10001',case_no:'00492268'],[project_no:'0-10160',case_no:'01957580'],[project_no:'1-10014',case_no:'02022686']]
def list2 = [[project_no:'0-10160',case_no:'01957590'],[project_no:'1-10014',case_no:'019126'],[project_no:'1-2896337',case_no:'02039596']]

def result = list1+list2
def projNos = result.inject([]) { keys, item ->  keys << item.project_no } as Set


def finalResult = []
projNos.each { proj ->
    //To avoid duplicate cases in project, using it as Set
    def cases = [] as Set
    result.each { item ->
        if (item.project_no == proj) {
            cases << item.case_no
        }
    }
    finalResult << [ 'project_no': proj, 'case_no' : cases ]
}

println finalResult

您可以快速在线试用 Demo