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")) // falseKotlin 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) // falseYou 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) // trueThe 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
MediumYou 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
nrepresenting the number of allowed usernames - Next
nlines: 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 grantedIf the username to check is david, the output should be:
Access deniedTry 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
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input14Lists Advanced
List Slicing With SubListList Slicing With Take DropSequence OperatorsThe Contains MethodRecap - Search a Page3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground