added a groupBy method (and stumbled on a couple more little compiler bugs which could well be the same as previous issues I've raised this week). Happy holidays everyone :)

This commit is contained in:
James Strachan
2011-12-24 07:46:26 +00:00
parent 8396017b5b
commit 393ecf2208
2 changed files with 32 additions and 0 deletions
+14
View File
@@ -81,6 +81,20 @@ inline fun <T> java.lang.Iterable<T>.foreach(operation: (element: T) -> Unit) {
operation(elem)
}
/**
* Iterates through the collection performing the transformation on each element and using the result
* as the key in a map to group elements by the result
*/
inline fun <T,K> java.lang.Iterable<T>.groupBy(result: Map<K,List<T>> = HashMap<K,List<T>>(), toKey: (T)-> K) : Map<K,List<T>> {
for (elem in this) {
val key = toKey(elem)
val list = result.getOrElseUpdate(key){ ArrayList<T>() }
list.add(elem)
}
return result
}
/** Creates a String from all the elements in the collection, using the seperator between them and using the given prefix and postfix if supplied */
inline fun <T> java.lang.Iterable<T>.join(separator: String, prefix: String = "", postfix: String = "") : String {
val buffer = StringBuilder(prefix)
+18
View File
@@ -118,6 +118,24 @@ class CollectionTest() : TestSupport() {
assertEquals(6, count)
}
fun testGroupBy() {
val words = arrayList("a", "ab", "abc", "def", "abcd")
/*
TODO inference engine should not need this type info?
*/
val byLength = words.groupBy<String,Int>{it.length}
assertEquals(4, byLength.size())
println("Grouped by length is: $byLength")
/*
TODO compiler bug...
val l3 = byLength.getOrElse(3, {ArrayList<String>()})
assertEquals(2, l3.size)
*/
}
fun testJoin() {
val text = data.join("-", "<", ">")
assertEquals("<foo-bar>", text)