class Foo {
Long a
Long b
Long c
String toString() { "(A:$a B:$b C:$c)" }
}
def ls = [
new Foo(a: 10, b: 9000, c: 3),
new Foo(a: 10, b: 30, c: 9),
new Foo(a: 10, b: 1000, c: 2),
new Foo(a: 10, b: 0, c: 1),
new Foo(a: 60, b: 80, c: 10),
new Foo(a: 60, b: 80, c: 2),
new Foo(a: 60, b: 30, c: 0),
]
def ls2 = ls.toList()
def ls3 = ls.toList()
// Apenas para comparação
def ordenacaoSimples = ls.sort { it.a }
// Forma "burra" (múltiplas iterações/loops)
def ordenacaoMultiplaSequencial = ls2.sort { it.c }.sort { it.b }.sort { it.a }
// Forma ideal (melhor desempenho)
def ordenacaoMultiplaClosureComparator = ls3.sort{ obj1, obj2 -> return (obj1.a <=> obj2.a) ?: (obj1.b <=> obj2.b) ?: (obj1.c <=> obj2.c) }
assert ordenacaoSimples != ordenacaoMultiplaSequencial
assert ordenacaoMultiplaSequencial == ordenacaoMultiplaClosureComparator
println "ordenacaoSimples : " + ordenacaoSimples
println "ordenacaoMultiplaSequencial : " + ordenacaoMultiplaSequencial
println "ordenacaoMultiplaClosureComparator: " + ordenacaoMultiplaClosureComparator
Posted by Bruno Vieira to ZeroGlosa (2018-02-20 12:13)