0

是否有一种“常规”方式通过第一个参数对集合进行排序,如果第一个参数在两个或多个元素中重复,则通过第二个参数(第二个参数是一个数组)对其进行排序?

例子:

编辑(子数组的长度是可变的):

[1, [1,2,3]]
[1, [4,6]]
[2, [1,2,3,4,5]]
[3, [1,2,3]]
[3, [ 1,2,4,5]]

提前致谢

4

2 回答 2

0

看看以下提姆耶茨要点

它展示了一种如何使用多个比较器对列表进行排序的方法。

对于您的示例:

Collection.metaClass.sort = { boolean mutate, Closure... closures ->
    delegate.sort( mutate ) { a, b ->
        closures.findResult { c -> c( a ) <=> c( b ) ?: null }
    }
} 

def list = [[3, [1,2,3]],
                [1, [4,5,6]],
                [2, [1,2,3]],
                [1, [1,2,3]],
                [3, [1,2,4]]]

assert list.sort(false, {it[0]}, {it[1][0]}, {it[1][1]}, {it[1][2]}) == [[1, [1,2,3]],
                                                                         [1, [4,5,6]],
                                                                         [2, [1,2,3]],
                                                                         [3, [1,2,3]],
                                                                         [3, [1,2,4]]] 

希望有帮助...

于 2012-11-19T21:43:24.563 回答
0

如果要构建自定义排序,可以使用 .sort:

def lis = []

lis << [3, [1,2,4]]
lis << [1, [1,2,3]]
lis << [3, [1,2,3]]
lis << [1, [4,5,6]]
lis << [2, [1,2,3]]

lis.sort{a,b->
    if(a[0]==b[0])
    {
        def aArray = a[1]
        def bArray = b[1]
        for(int i=0;i<aArray.size();i++)
        {
            if(bArray[i])
            {
                if(aArray[i]!=bArray[i])
                {
                    return aArray[i]<=>bArray[i]
                }
            }
            else
            {
                return 1
            }
        }    
        return 0
    }
    else
        return a[0]<=>b[0]
}


lis.each{x->
println x
}

I didn't really deal well with the case that the lists are different lengths you could improve on that for your apps needs.

于 2012-11-19T21:50:27.753 回答