2016-05-16 99 views
65

假設我有一個人員列表,我需要先按Age分類然後按名稱排序。在Kotlin中對多個字段進行排序

從C#-background的到來,我可以很容易地做到這一點的說,通過使用LINQ語言:

var list=new List<Person>(); 
list.Add(new Person(25, "Tom")); 
list.Add(new Person(25, "Dave")); 
list.Add(new Person(20, "Kate")); 
list.Add(new Person(20, "Alice")); 

//will produce: Alice, Kate, Dave, Tom 
var sortedList=list.OrderBy(person => person.Age).ThenBy(person => person.Name).ToList(); 

怎樣才能做到這一點使用科特林?

這是我試過

val sortedList = ArrayList(list.sortedBy { it.age }.sortedBy { it.name })) //wrong 

回答

110

sortedWith + compareBy((因爲第一個「sortedBy」條款的輸出得到由第二個導致按名稱排序的列表僅覆蓋這顯然是錯誤的)以lambda表達式的可變參數)做的伎倆:

val sortedList = list.sortedWith(compareBy({ it.age }, { it.name })) 

您還可以使用稍微更簡潔的可調用的參考語法:

val sortedList = list.sortedWith(compareBy(Person::age, Person::name)) 
+1

Kotlin是天賜之物 – ElliotM

38

使用sortedWith可以用Comparator對列表進行排序。

然後,可以使用多種方法構造一個比較:

  • compareBythenBy構造比較器中調用鏈:

    list.sortedWith(compareBy<Person> { it.age }.thenBy { it.name }.thenBy { it.address }) 
    
  • compareBy具有過載這需要多種功能:

    list.sortedWith(compareBy({ it.age }, { it.name }, { it.address })) 
    
+0

謝謝,這就是我一直在尋找的!我對kotlin有點新,爲什麼你需要在你的第一個項目符號中有'compareBy '而不是'compareBy'? – Aneem

+0

@Aneem,Kotlin編譯器有時無法推斷出類型參數,需要手動指定。其中一種情況是,當一個泛型類型被期望時,你想傳遞泛型函數調用鏈的結果,比如'compareBy {it.age} .thenBy {it.name} .thenBy {it.address}'。第二點,只有一個函數調用,沒有調用鏈接:'compareBy({it.age},{it.name},{it.address})''。 – hotkey

相關問題