Introduce associateWith and associateWithTo functions

#KT-13814
This commit is contained in:
Ilya Gorbunov
2018-08-20 22:01:12 +03:00
parent 751e844258
commit f367322084
10 changed files with 211 additions and 0 deletions
@@ -358,6 +358,18 @@ class CollectionTest {
assertEquals(namesByTeam, mutableNamesByTeam)
}
@Test fun associateWith() {
val items = listOf("Alice", "Bob", "Carol")
val itemsWithTheirLength = items.associateWith { it.length }
assertEquals(mapOf("Alice" to 5, "Bob" to 3, "Carol" to 5), itemsWithTheirLength)
val updatedLength =
items.drop(1).associateWithTo(itemsWithTheirLength.toMutableMap()) { name -> name.toLowerCase().count { it in "aeuio" }}
assertEquals(mapOf("Alice" to 5, "Bob" to 1, "Carol" to 2), updatedLength)
}
@Test fun plusRanges() {
val range1 = 1..3
val range2 = 4..7
@@ -548,6 +548,18 @@ public class SequenceTest {
assertEquals(listOf("act", "wast", "test"), sequenceOf("act", "test", "wast").sortedWith(comparator).toList())
}
@Test fun associateWith() {
val items = sequenceOf("Alice", "Bob", "Carol")
val itemsWithTheirLength = items.associateWith { it.length }
assertEquals(mapOf("Alice" to 5, "Bob" to 3, "Carol" to 5), itemsWithTheirLength)
val updatedLength =
items.drop(1).associateWithTo(itemsWithTheirLength.toMutableMap()) { name -> name.toLowerCase().count { it in "aeuio" }}
assertEquals(mapOf("Alice" to 5, "Bob" to 1, "Carol" to 2), updatedLength)
}
@Test fun orEmpty() {
val s1: Sequence<Int>? = null
assertEquals(emptySequence(), s1.orEmpty())
+8
View File
@@ -1159,6 +1159,14 @@ class StringTest {
assertEquals(listOf('A', 'A', 'B', 'D'), result[true])
}
@Test fun associateWith() = withOneCharSequenceArg("abc") { data ->
val result = data.associateWith { it + 1 }
assertEquals(mapOf('a' to 'b', 'b' to 'c', 'c' to 'd'), result)
val mutableResult = data.drop(1).associateWithTo(result.toMutableMap()) { it - 1 }
assertEquals(mapOf('a' to 'b', 'b' to 'a', 'c' to 'b'), mutableResult)
}
@Test fun joinToString() {
val data = "abcd".toList()
val result = data.joinToString("_", "(", ")")