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
@@ -300,6 +300,14 @@ class Collections {
class Transformations {
@Sample
fun associateWith() {
val words = listOf("a", "abc", "ab", "def", "abcd")
val withLength = words.associateWith { it.length }
assertPrints(withLength.keys, "[a, abc, ab, def, abcd]")
assertPrints(withLength.values, "[1, 3, 2, 3, 4]")
}
@Sample
fun groupBy() {
val words = listOf("a", "abc", "ab", "def", "abcd")
@@ -84,6 +84,15 @@ class Strings {
assertPrints(result, "[az, by, cx]")
}
@Sample
fun associateWith() {
val string = "bonne journée"
// associate each character with its code
val result = string.associateWith { char -> char.toInt() }
// notice each letter occurs only once
assertPrints(result, "{b=98, o=111, n=110, e=101, =32, j=106, u=117, r=114, é=233}")
}
@Sample
fun stringToByteArray() {
val charset = Charsets.UTF_8