如何根据已按降序排序的映射按降序对列表进行排序

时间:2018-02-06 04:24:55

标签: groovy

我有一个类似于:

的JSON数组(地图列表)
def listOfMap = [[TESTCASE:1, METHOD:'CLICK', RESULT:'PASS'],  
      [TESTCASE:2, METHOD:'CLICK', RESULT:'FAIL'],  
      [TESTCASE:3, METHOD:'CLICK', RESULT:'FAIL'],   
      [TESTCASE:4, METHOD:'TYPETEXT', RESULT:'FAIL']]

我按METHOD名称分组并收集每种方法的失败百分比

def percentage (map){
     (map.FAIL ?: 0) / ((map.PASS ?: 0) + (map.FAIL ?: 0)) * 100
}

def result = listOfMap.groupBy{it.METHOD}
                      .collectEntries{[(it.key) : percentage(it.value.countBy{it.RESULT})]}

现在我的输出将是[CLICK:66.6,TYPETEXT:100]

按百分比的降序对上述结果进行排序,

def sortedResult = result.sort { a, b -> b.value <=> a.value }

现在我的输出将是[TYPETEXT:100,CLICK:66.6]

如何获得与上述排序顺序相关的METHOD的FAIL计数和PASS计数?

我的输出应该是两个单独的列表(按故障%的降序排序)

passList  = [0, 1]     Note : [TYPETEXT passed 0 times, CLICK passed 1 time]
failList =  [1, 2]     Note : [TYPETEXT failed 1 time, CLICK failed 2 times]

基本上我正在寻找这些数据来创建一个类似于以下列表的CSV报告:

CSV Report

2 个答案:

答案 0 :(得分:1)

鉴于此(来自原始帖子):

def listOfMap = [[TESTCASE:1, METHOD:'CLICK', RESULT:'PASS'],  
      [TESTCASE:2, METHOD:'CLICK', RESULT:'FAIL'],  
      [TESTCASE:3, METHOD:'CLICK', RESULT:'FAIL'],   
      [TESTCASE:4, METHOD:'TYPETEXT', RESULT:'FAIL']]

考虑使用Expando,以便percentage是一个字段,还有passCountfailCount

def percentage(passCount, failCount) {
    failCount / (passCount + failCount) * 100
}

def result = listOfMap.groupBy{it.METHOD}.collectEntries{
                def rec = new Expando()
                def count = it.value.countBy{ it.RESULT } 

                rec."passCount" = count.'PASS' ?: 0
                rec."failCount" = count.'FAIL' ?: 0
                rec."percentage" = percentage(rec."passCount",
                                              rec."failCount")

                [(it.key) : rec]
             }

def sortedResult = result.sort { a, b -> 
                       b.value."percentage" <=> a.value."percentage" 
                   }
sortedResult.each { println it }

输出与CSV所需的基本架构匹配:

$ groovy Example.groovy 
TYPETEXT={failCount=1, percentage=100, passCount=0}
CLICK={failCount=2, percentage=66.6666666700, passCount=1}

答案 1 :(得分:0)

您可以进行多重分组,让您的生活更轻松:

def listOfMap = [[TESTCASE: 1, METHOD: 'CLICK', RESULT: 'PASS'],
    [TESTCASE: 2, METHOD: 'CLICK', RESULT: 'FAIL'],
    [TESTCASE: 3, METHOD: 'CLICK', RESULT: 'FAIL'],
    [TESTCASE: 4, METHOD: 'TYPETEXT', RESULT: 'FAIL']]

def result = listOfMap.groupBy({ it.METHOD }, { it.RESULT })
                      .collectEntries { method, r ->
    def passCount = r.PASS?.size() ?: 0
    def failCount = r.FAIL?.size() ?: 0
    [method, [passCount: passCount, failCount: failCount, failPercentage: (failCount / (passCount + failCount) * 100.0)]]
}.sort { -it.value.failPercentage }

然后你可以这样做:

result.values().failCount

result.values().passCount

获取问题所需的数字。

最好永远不要尝试以相同的顺序保存多个单独的列表,更容易将所有数据存储在一起,并在对整个事物进行排序后提取它