renamed the rather long getOrElseUpdate to a simpler getOrPut which is a bit simpler and more accurate; as a new entry is put into the Map if its null
This commit is contained in:
@@ -110,7 +110,7 @@ inline fun <T> java.lang.Iterable<T>.foldRight(initial: T, operation: (it: T, it
|
||||
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>() }
|
||||
val list = result.getOrPut(key){ ArrayList<T>() }
|
||||
list.add(elem)
|
||||
}
|
||||
return result
|
||||
|
||||
@@ -19,8 +19,9 @@ inline fun linkedList<T>(vararg values: T) : LinkedList<T> = values.to(LinkedLi
|
||||
/** Returns a new HashSet with a variable number of initial elements */
|
||||
inline fun hashSet<T>(vararg values: T) : HashSet<T> = values.to(HashSet<T>(values.size))
|
||||
|
||||
/** Returns a new hash map */
|
||||
inline fun <K,V> hashMap() = HashMap<K,V>()
|
||||
inline fun <K,V> hashMap(): HashMap<K,V> = HashMap<K,V>()
|
||||
|
||||
inline fun <K,V> sortedMap(): SortedMap<K,V> = TreeMap<K,V>()
|
||||
|
||||
|
||||
val Collection<*>.indices : IntRange
|
||||
|
||||
@@ -41,7 +41,7 @@ inline fun <K,V> java.util.Map<K,V>.getOrElse(key: K, defaultValue: ()-> V) : V
|
||||
}
|
||||
|
||||
/** Returns the value for the given key or the result of the defaultValue function is put into the map for the given value and returned */
|
||||
inline fun <K,V> java.util.Map<K,V>.getOrElseUpdate(key: K, defaultValue: ()-> V) : V {
|
||||
inline fun <K,V> java.util.Map<K,V>.getOrPut(key: K, defaultValue: ()-> V) : V {
|
||||
val current = this.get(key)
|
||||
if (current != null) {
|
||||
return current
|
||||
|
||||
@@ -21,11 +21,11 @@ class MapTest() : TestSupport() {
|
||||
assertEquals(0, data.size)
|
||||
}
|
||||
|
||||
fun testGetOrElseUpdate() {
|
||||
val a = data.getOrElseUpdate("foo"){2}
|
||||
fun testGetOrPut() {
|
||||
val a = data.getOrPut("foo"){2}
|
||||
assertEquals(2, a)
|
||||
|
||||
val b = data.getOrElseUpdate("foo"){3}
|
||||
val b = data.getOrPut("foo"){3}
|
||||
assertEquals(2, b)
|
||||
|
||||
assertEquals(1, data.size())
|
||||
|
||||
Reference in New Issue
Block a user