Not able to sort the following array tried solutions are listed. Initial we will have list, by finding the position in another list new list is created
def mylist=[]
def mylistData=[:]
mylistData.id="61628d82a174599d7ae7c61bf6d216f22d5139da"
mylist.add(mylistData)
mylistData=[:]
mylistData.id="0cc18d6d3c93240ab93457063b4974a1270104c0"
mylist.add(mylistData)
mylistData=[:]
mylistData.id="bb007a1c9f594b55662a5b36d5f5b1a7651f3b0f"
mylist.add(mylistData)
mylistData=[:]
mylistData.id="087e7538583ee261944b66491391947d3a002380"
mylist.add(mylistData)
mylistData=[:]
mylistData.id="587ee2b1482509e12d5657bc55db70c9b482eddd"
mylist.add(mylistData)
def list=[]
//linesList=["587ee2b1482509e12d5657bc55db70c9b482eddd"] //contains 50 such values
for(item in mylist){
item.pos=linesList.findIndexOf { it == item.id }.toInteger()
list.add(item)
}
list.sort{ it.pos }
println list // list is not sorted
println list.sort{ it.pos } // list is not sorted
Expected result:
[{id=587ee2b1482509e12d5657bc55db70c9b482eddd, pos=0},{id=bb007a1c9f594b55662a5b36d5f5b1a7651f3b0f, pos=19}, {id=087e7538583ee261944b66491391947d3a002380, pos=37},
{id=61628d82a174599d7ae7c61bf6d216f22d5139da, pos=45},{id=0cc18d6d3c93240ab93457063b4974a1270104c0, pos=54}]
Actual
[{id=61628d82a174599d7ae7c61bf6d216f22d5139da, pos=45}, {id=0cc18d6d3c93240ab93457063b4974a1270104c0, pos=54}, {id=bb007a1c9f594b55662a5b36d5f5b1a7651f3b0f, pos=19}, {id=087e7538583ee261944b66491391947d3a002380, pos=37}, {id=587ee2b1482509e12d5657bc55db70c9b482eddd, pos=0}]
Tried solutions
list.sort{ it.pos }
Note: I am facing this issue while running inside jenkins
It's a CPS artifact, see here. For your sorting to work you need to put it inside a NonCPS annotated method:
...
println list // list is not sorted
sortByPos(list)
println list // list is sorted
@NonCPS
def sortByPos(l) {
l.sort { it.pos }
}
Oh, and lists in groovy are sorted in place.