kotlin mutableMapでmapが空であるかを判定する

kotlin mutableMapでmapが空であるかを判定する

kotlinで、mutableMapでmapが空であるかを判定する手順を記述してます。

環境

  • OS windows11 home
  • java 17.0.2
  • kotlin 1.6.10-release-923

手順

mutamutableMapでmapが空であるかを判定するには、「isEmpty」で可能です。

map名.isEmpty()

実際に、使用してみます。

fun main() {

    val m = mutableMapOf('a' to 1, 'b' to 2, 'c' to 3, 'd' to 4, 'e' to 5)
    val m2: Map<Char, Int>  = mutableMapOf()
    val m3: Map<Char?, Int?>  = mutableMapOf(null to null)
    
    println( m.isEmpty() ) // false
    println( m2.isEmpty() ) // true
    println( m3.isEmpty() ) // false  

}

判定されていることが確認できます。

isNotEmpty

「isNotEmpty」を使用すると、判定結果は逆になります。

fun main() {

    val m = mutableMapOf('a' to 1, 'b' to 2, 'c' to 3, 'd' to 4, 'e' to 5)
    val m2: Map<Char, Int>  = mutableMapOf()
    val m3: Map<Char?, Int?>  = mutableMapOf(null to null)
    
    println( m.isNotEmpty() ) // true
    println( m2.isNotEmpty() ) // false
    println( m3.isNotEmpty() ) // true  

}

none

要素が空であるかを判定する「none」を使用しても結果は同じになります。

fun main() {

    val m = mutableMapOf('a' to 1, 'b' to 2, 'c' to 3, 'd' to 4, 'e' to 5)
    val m2: Map<Char, Int>  = mutableMapOf()
    val m3: Map<Char?, Int?>  = mutableMapOf(null to null, 'a' to 1, 'b' to 2)
        
    println( m.none() )  // false
    println( m2.none() ) // true
    println( m3.none() ) // false

}