Kotlin Map none()
Syntax & Examples
Syntax of Map.none()
There are 2 variations for the syntax of Map.none() extension function. They are:
1.
fun <K, V> Map<out K, V>.none(): Boolean
This extension function returns true if the map has no entries.
2.
fun <K, V> Map<out K, V>.none( predicate: (Entry<K, V>) -> Boolean ): Boolean
This extension function returns true if no entries match the given predicate.
✐ Examples
1 Check if map is empty
In this example,
- We create a map named
map1
containing integer keys and character values. - We then apply the
none()
function onmap1
. - As a result,
true
is returned if the map has no entries. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val result = map1.none()
println(result)
}
Output
false
2 Check if any even values exist in the map
In this example,
- We create a map named
map2
containing character keys and integer values. - We then apply the
none()
function onmap2
with a predicate checking for even values. - As a result,
false
is returned if any even values exist in the map. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
val result = map2.none { it.value % 2 == 0 }
println(result)
}
Output
false
3 Check if any keys are greater than 3 in the map
In this example,
- We create a map named
map3
containing integer keys and character values. - We then apply the
none()
function onmap3
with a predicate checking for keys greater than 3. - As a result,
true
is returned if no keys greater than 3 exist in the map. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map3 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val result = map3.none { it.key > 3 }
println(result)
}
Output
true
Summary
In this Kotlin tutorial, we learned about none() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.