Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

linkedhashmap
containsvalue
communitycreator
kotlin

How to check if LinkedHashMap contains a value in Kotlin

Programming Bytes

In Kotlin, the containsValue() method is used to check if the LinkedHashMap contains a value passed as an argument.

Syntax

fun containsValue(value: V): Boolean
Syntax of the containsValue method

Parameters

This method takes value as an argument.

Return value

This method returns true if the value is mapped to one or more keys. If not, it returns false.

Example

fun main() {
  //create a new LinkedHashMap which can have string type as key, and int type as value
  val map: LinkedHashMap<Int, String> = linkedMapOf()
  map.put(1, "one")
  map.put(2, "two")
  println("The map is : $map")
  print("Checking if the map has value 'one' : ")
  var hasValue: Boolean = map.containsValue("one")
  println(hasValue)

  hasValue = map.containsValue("three")
  print("Checking if the map has value 'three' : ")
  println(hasValue)

}
Using containsValue to check if the map has a specific value

Explanation

  • Line 3: We create a LinkedHashMap object with the name map. We use the linkedMapOf method to create an empty LinkedHashMap.

  • Lines 4 and 5: We use the put() method to add two new entries {1=one, 2=two} to the map.

  • Line 8: We use the containsValue() method with one as an argument. This checks if the map has an entry with the value one. In our case, it returns true.

  • Line 11: We use the containsValue() method with three as an argument. This checks if the map has an entry with the value three. In our case, it returns false.

RELATED TAGS

linkedhashmap
containsvalue
communitycreator
kotlin
RELATED COURSES

View all Courses

Keep Exploring