Search code examples
jenkinsgroovyjenkins-pipeline

Sort map by value in Groovy jenkins pipeline script


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


Solution

  • 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)