added a linkedMap() function to help create LinkedHashMap objects to maintain map insertion order

This commit is contained in:
James Strachan
2012-04-16 17:52:02 +01:00
parent f8d50fd9bb
commit 378c95baa3
2 changed files with 40 additions and 1 deletions
+22 -1
View File
@@ -30,7 +30,7 @@ public inline fun sortedSet<T>(vararg values: T) : TreeSet<T> = values.to(TreeSe
* @includeFunctionBody ../../test/MapTest.kt createUsingTuples
*/
public inline fun <K,V> hashMap(vararg values: #(K,V)): HashMap<K,V> {
val answer = HashMap<K,V>()
val answer = HashMap<K,V>(values.size)
/**
TODO replace by this simpler call when we can pass vararg values into other methods
answer.putAll(values)
@@ -44,6 +44,8 @@ public inline fun <K,V> hashMap(vararg values: #(K,V)): HashMap<K,V> {
/**
* Returns a new [[SortedMap]] populated with the given tuple values where the first value in each tuple
* is the key and the second value is the value
*
* @includeFunctionBody ../../test/MapTest.kt createSortedMap
*/
public inline fun <K,V> sortedMap(vararg values: #(K,V)): SortedMap<K,V> {
val answer = TreeMap<K,V>()
@@ -57,6 +59,25 @@ public inline fun <K,V> sortedMap(vararg values: #(K,V)): SortedMap<K,V> {
return answer
}
/**
* Returns a new [[LinkedHashMap]] populated with the given tuple values where the first value in each tuple
* is the key and the second value is the value. This map preserves insertion order so iterating through
* the map's entries will be in the same order
*
* @includeFunctionBody ../../test/MapTest.kt createLinkedHashMap
*/
public inline fun <K,V> linkedMap(vararg values: #(K,V)): LinkedHashMap<K,V> {
val answer = LinkedHashMap<K,V>(values.size)
/**
TODO replace by this simpler call when we can pass vararg values into other methods
answer.putAll(values)
*/
for (v in values) {
answer.put(v._1, v._2)
}
return answer
}
val Collection<*>.indices : IntRange
get() = 0..size-1
+18
View File
@@ -119,6 +119,24 @@ class MapTest {
assertEquals(2, map.get("b"))
}
test fun createLinkedMap() {
val map = linkedMap(#("c", 3), #("b", 2), #("a", 1))
assertEquals(3, map.size)
assertEquals(1, map.get("a"))
assertEquals(2, map.get("b"))
assertEquals(3, map.get("c"))
assertEquals(arrayList("c", "b", "a"), map.keySet().toList())
}
test fun createSortedMap() {
val map = sortedMap(#("c", 3), #("b", 2), #("a", 1))
assertEquals(3, map.size)
assertEquals(1, map.get("a"))
assertEquals(2, map.get("b"))
assertEquals(3, map.get("c"))
assertEquals(arrayList("a", "b", "c"), map.keySet()!!.toList())
}
/**
TODO
test case for http://youtrack.jetbrains.com/issue/KT-1773