kotlin mutableMapに指定した条件以外のkeyと値を取得する

kotlin mutableMapに指定した条件以外のkeyと値を取得する

kotlinで、mutableMapに指定した条件以外のkeyと値を取得する手順を記述してます。「filterNot」に条件を指定することで可能です。「filterNotTo」を使用すれば別の「Map」として結果を追加することもできます。

環境

  • OS windows11 home
  • java 19.0.1
  • kotlin 1.7.20-release-201

手順

mutableMapに指定した条件以外のkeyと値を取得するには、「filterNot」で可能です。

map名.filterNot({ 条件 })

実際に、取得してみます。

fun main() {

    val m = mutableMapOf('a' to 1, 'b' to 2, 'c' to 3, 'd' to 4, 'e' to 5)

    println( m.filterNot { it.key == 'a' }  ) // {b=2, c=3, d=4, e=5}
    println( m.filterNot { it.value > 2 && it.value < 5 }  ) // {a=1, b=2, e=5}

}

取得されていることが確認できます。

条件が存在しない場合は、全ての値が取得されます。

fun main() {

    val m = mutableMapOf('a' to 1, 'b' to 2, 'c' to 3, 'd' to 4, 'e' to 5)

    println( m.filterNot { it.key == 'f' }  ) // {a=1, b=2, c=3, d=4, e=5}

}

filterNotTo

filterNotToを使用すると、別のmapにその結果を追加することが可能です。

fun main() {

    val m = mutableMapOf('a' to 1, 'b' to 2, 'c' to 3, 'd' to 4, 'e' to 5)
    val m2 = mutableMapOf('f' to 6)

    m.filterNotTo(m2) { it.key == 'a' }
    
    println( m2 ) // {f=6, b=2, c=3, d=4, e=5}

}