2013-12-09 60 views
2

我有列出哪種類型Person對象:順序列表

class Person{ 
    int id 
    String name 
    String bestColor 
} 


def persons = [ new Person(1,'Abdennour','white'), 
       new Person(2,'Ali','red'), 
       new Person(3,'Hsen','white'), 
       new Person(4,'Aicha','green') ] 

和我有顏色的列表:

def colors=['green','white','red'] 

我想根據第3字段訂購persons列表(bestColor)。但是,我不想按字母順序排列顏色,而是我想要與colors列表相同的順序。 這意味着,該預期的結果:

def persons=[new Person(4,'Aicha','green') 
,new Person(1,'Abdennour','white') 
,new Person(3,'Hsen','white') 
,new Person(2,'Ali','red')] 

回答

2

所以給出:

@groovy.transform.Canonical 
class Person{ 
    int id 
    String name 
    String bestColor 
} 

def persons = [ new Person(1, 'Abdennour', 'white'), 
       new Person(2, 'Ali', 'red'), 
       new Person(3, 'Hsen', 'white'), 
       new Person(4, 'Aicha', 'green') ] 

def colors = [ 'green','white','red' ] 

你可以這樣做:

// Sort (mutating the persons list) 
persons.sort { colors.indexOf(it.bestColor) } 

// check it's as expected 
assert persons.id == [ 4, 1, 3, 2 ] 
+0

真的,謝謝! –