「kotlin」mapValuesでマップ要素の値をまとめて変更するサンプル

環境
Windows11 pro 64bit
java 17.0.2
kotlin 1.6.10-release-923

構文
map名.mapValues{ it.value }
mapValuesを使って、マップ要素の値をまとめて変更します。
ラムダ式は、変更後の要素の値が戻り値になるように実装します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
fun main() {
val m = mutableMapOf('s' to 11, 't' to 22, 'y' to 33)
println( m.mapValues{it.value * 2} )
println( m.mapValues{it.value + 2} )
}
fun main() { val m = mutableMapOf('s' to 11, 't' to 22, 'y' to 33) println( m.mapValues{it.value * 2} ) println( m.mapValues{it.value + 2} ) }
fun main() { 
    val m = mutableMapOf('s' to 11, 't' to 22, 'y' to 33)    
        
    println( m.mapValues{it.value * 2} ) 
    println( m.mapValues{it.value + 2} ) 
}

実行結果
{s=22, t=44, y=66}
{s=13, t=24, y=35}

Kotlin

Posted by arkgame