Sort map by value in Groovy jenkins pipeline script

陌路散爱 提交于 2020-08-10 19:13:09

问题


How to do custom sort of Map for example by value in Jekins pipeline script?

This code doesn't quite work in Jenkins pipeline script:

Map m =[ james  :"silly boy",
         janny  :"Crazy girl",
         jimmy  :"funny man",
         georges:"massive fella" ]

Map sorted = m.sort { a, b -> a.value <=> b.value }

The map is still not sorted.

I decided to crate a separate question with better name and tags, because many people were struggling to find an answer here: Groovy custom sort a map by value


回答1:


You will have to create a separate method with @NonCPS annotation for that:

@NonCPS
def getSorted(def toBeSorted){
    toBeSorted.sort(){ a, b -> b.value <=> a.value }
}

And then call it from the pipeline script.

Map unsortedMap =[ james  :"silly boy",
         janny  :"Crazy girl",
         jimmy  :"funny man",
         georges:"massive fella" ]
def sortedMap = getSorted(unsortedMap)


来源:https://stackoverflow.com/questions/63121651/sort-map-by-value-in-groovy-jenkins-pipeline-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!