From 019962b6546d110852a17c7be25274d1ccc6793d Mon Sep 17 00:00:00 2001 From: Alexander Zolotov Date: Sun, 24 Jun 2012 17:56:46 +0400 Subject: [PATCH] Add sortBy method for interables --- .../stdlib/src/kotlin/JLangIterablesSpecial.kt | 13 +++++++++++++ libraries/stdlib/test/CollectionTest.kt | 11 +++++++++++ 2 files changed, 24 insertions(+) diff --git a/libraries/stdlib/src/kotlin/JLangIterablesSpecial.kt b/libraries/stdlib/src/kotlin/JLangIterablesSpecial.kt index adc2be1e622..fab0cfed4e9 100644 --- a/libraries/stdlib/src/kotlin/JLangIterablesSpecial.kt +++ b/libraries/stdlib/src/kotlin/JLangIterablesSpecial.kt @@ -71,6 +71,19 @@ public fun java.lang.Iterable.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 > java.lang.Iterable.sortBy(f: (T) -> R): java.util.List { + 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. * diff --git a/libraries/stdlib/test/CollectionTest.kt b/libraries/stdlib/test/CollectionTest.kt index d80743a32d2..030d5f081d9 100644 --- a/libraries/stdlib/test/CollectionTest.kt +++ b/libraries/stdlib/test/CollectionTest.kt @@ -445,6 +445,17 @@ class CollectionTest { // assertFalse(IterableWrapper(linkedList()).contains(15)) } + test fun sortBy() { + expect(arrayList("two" to 2, "three" to 3)) { + arrayList("three" to 3, "two" to 2).sortBy { it._2 } + } + expect(arrayList("three" to 3, "two" to 2)) { + arrayList("three" to 3, "two" to 2).sortBy { it._1 } + } + expect(arrayList("two" to 2, "three" to 3)) { + arrayList("three" to 3, "two" to 2).sortBy { it._1.length } + } + } class IterableWrapper(collection : java.lang.Iterable) : java.lang.Iterable { private val collection = collection