Kotlin Tutorials

Kotlin Map containsValue()
Syntax & Examples

Syntax of Map.containsValue()

The syntax of Map.containsValue() function is:

abstract fun containsValue(value: V): Boolean

This containsValue() function of Map returns true if the map maps one or more keys to the specified value.



✐ Examples

1 Check if map contains the specified character value

In this example,

  • We create a map named map with integer keys and character values.
  • We use the containsValue() function to check if the map contains the value 'b'.
  • The result, which is true or false, is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
    val result = map.containsValue('b')
    println(result)
}

Output

true

2 Check if map contains the specified integer value

In this example,

  • We create a map named map with string keys and integer values.
  • We use the containsValue() function to check if the map contains the value 2.
  • The result, which is true or false, is printed to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
    val result = map.containsValue(2)
    println(result)
}

Output

true

3 Print the result of containsValue for a specific value

In this example,

  • We create a map named map with integer keys and character values.
  • We directly print whether the map contains the value 'c' using string interpolation.
  • The result, which is true or false, is interpolated into the output string.

Kotlin Program

fun main(args: Array<String>) {
    val map = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
    println("Contains 'c': ${map.containsValue('c')}")
}

Output

Contains 'c': true

Summary

In this Kotlin tutorial, we learned about containsValue() function of Map: the syntax and few working examples with output and detailed explanation for each example.