在Groovy中使用自定义比较器对Map进行排序

dfuffjeb  于 2022-11-21  发布在  其他
关注(0)|答案(1)|浏览(148)
final_map = ["/7amd64-Aug2022.1":"2022-08-09","/7amd64-Oct2022.1":"2022-10-12","/7":"2022-11-08","/7amd64-Jul2022.1":"2022-07-12","/7amd64":"2022-11-08","/7amd64-June2022.1":"2022-06-14","/7amd64-beta":"2022-11-08","/7amd64-Sep2022.1":"2022-09-14","/7amd64-Nov2022.1":"2022-11-08","/_uploads":"2022-11-08"]

Jenkins管道(下面是我的代码,这是不工作)

result = final_map.sort { a,b -> a.value <=> b.value }
echo "Output: ${result}"

期望使用日期(值)对Map进行排序。

f3temu5u

f3temu5u1#

您可以为此使用自定义比较器。检查以下Groovy代码。

final_map = ["/7amd64-Aug2022.1":"2022-08-09","/7amd64-Oct2022.1":"2022-10-12","/7":"2022-11-08","/7amd64-Jul2022.1":"2022-07-12","/7amd64":"2022-11-08","/7amd64-June2022.1":"2022-06-14","/7amd64-beta":"2022-11-08","/7amd64-Sep2022.1":"2022-09-14","/7amd64-Nov2022.1":"2022-11-08","/_uploads":"2022-11-08"]

final_map.sort { s1, s2 -> 

        def s1Date = new Date(s1.value.replace('-', '/'))
        def s2Date = new Date(s2.value.replace('-', '/'))
 
        if( s1Date.before(s2Date)) {
            return -1
        } else {
            return 1
        } 
    }
println final_map

相关问题