Menu
Coddy logo textTech

The Contains Method

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 82 of 93.

A common task when working with lists is checking whether a specific element exists in the collection. Kotlin provides the contains() method for this purpose, which returns true if the element is found and false otherwise.

val fruits = listOf("Apple", "Banana", "Orange")
println(fruits.contains("Banana"))  // true
println(fruits.contains("Grape"))   // false

Kotlin also offers a more readable alternative using the in operator, which does exactly the same thing:

val numbers = listOf(1, 2, 3, 4, 5)
println(3 in numbers)   // true
println(10 in numbers)  // false

You can also check if an element is not in a list using !in:

val colors = listOf("Red", "Green", "Blue")
if ("Yellow" !in colors) {
    println("Yellow is not available")
}

These checks work with strings too, allowing you to verify if a character or substring exists:

val word = "Kotlin"
println('K' in word)      // true
println("otl" in word)    // true

The in operator is particularly useful in conditional statements, making your code more expressive and easier to read than manually iterating through a list to find an element.

challenge icon

Challenge

Medium

You will receive a list of allowed usernames and a username to check. Determine if the username exists in the allowed list using the in operator.

If the username is in the list, print Access granted. If the username is not in the list, print Access denied.

Input format:

  • First line: an integer n representing the number of allowed usernames
  • Next n lines: strings representing the allowed usernames
  • Last line: the username to check

Output format:

Print either Access granted or Access denied based on whether the username exists in the allowed list.

Example:

If the allowed list is ["alice", "bob", "charlie"] and the username to check is bob, the output should be:

Access granted

If the username to check is david, the output should be:

Access denied

Try it yourself

fun main() {
    // Read the number of allowed usernames
    val n = readLine()!!.toInt()
    
    // Read the allowed usernames into a list
    val allowedUsernames = mutableListOf<String>()
    for (i in 1..n) {
        allowedUsernames.add(readLine()!!)
    }
    
    // Read the username to check
    val usernameToCheck = readLine()!!
    
    // TODO: Write your code below
    // Use the 'in' operator to check if usernameToCheck exists in allowedUsernames
    // Print "Access granted" if found, "Access denied" if not
    
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground