Add sortBy method for interables

This commit is contained in:
Alexander Zolotov
2012-06-24 17:56:46 +04:00
parent 72ef07acef
commit 019962b654
2 changed files with 24 additions and 0 deletions
@@ -71,6 +71,19 @@ public fun <T> java.lang.Iterable<T>.last() : T {
return last;
}
/**
* Copies all elements into a [[List]] and sorts it by value of compare_function(element)
*
* E.g. arrayList("two" to 2, "one" to 1).sortBy({it._2}) returns list sorted by second element of tuple
*
* @includeFunctionBody ../../test/CollectionTest.kt sortBy
*/
public inline fun <in T, R: Comparable<in R>> java.lang.Iterable<T>.sortBy(f: (T) -> R): java.util.List<T> {
val sortedList = this.toList()
java.util.Collections.sort(sortedList, comparator {(x, y) -> f(x).compareTo(f(y))})
return sortedList
}
/**
* Checks if collection contains given item.
*