Question

Check Whether a String Array Contains a Value in Kotlin

kotlinarrays

Question

How can I check whether an array of strings contains a particular value in Kotlin, similar to Ruby's include? method?

For example, I considered the following approach:

array.filter { it == "value" }.any()

Is there a more direct or idiomatic way to do this?

Short Answer

You will learn Kotlin's idiomatic membership checks for string arrays: the in operator and contains() function. You will also see when to use any { ... } for conditions, why filter().any() is wasteful for a simple lookup, and how string equality works in Kotlin.

Concept

To test whether an array contains an exact value, Kotlin provides two direct options:

"value" in array
array.contains("value")

They mean the same thing. The in form is usually easier to read in a condition.

val fruits = arrayOf("apple", "banana", "orange")

if ("banana" in fruits) {
    println("Found it")
}

For strings, Kotlin's == compares content rather than object identity. Therefore, two separate string objects containing the same characters are considered equal.

Your approach works:

array.filter { it == "value" }.any()

However, filter creates a new collection containing all matches, then any() checks whether that new collection is non-empty. If all you need is a yes/no answer, use in, contains(), or any { ... } instead.

Mental Model

Think of an array as a row of labelled drawers.

  • "banana" in fruits asks: “Is there a drawer labelled banana?”
  • fruits.contains("banana") asks the same question in a method-call style.
  • fruits.any { it.startsWith("b") } asks a broader question: “Does any drawer have a label that starts with b?”
  • filter { ... } first gathers every matching drawer into a new box. That is useful when you need the matches themselves, but unnecessary when you only need to know whether one exists.
Take Quiz

Syntax and Examples

Use in for an exact membership check:

val roles = arrayOf("admin", "editor", "viewer")

val canEdit = "editor" in roles
println(canEdit) // true

Use contains() when you prefer an explicit function name:

val roles = arrayOf("admin", "editor", "viewer")

println(roles.contains("guest")) // false

Use any { ... } when the check is based on a condition instead of one exact value:

val filenames = arrayOf("report.pdf", "photo.jpg", "notes.txt")

val hasPdf = filenames.any { it.endsWith(".pdf") }
println(hasPdf) // true

any stops as soon as it finds a matching element, so it is appropriate for existence checks.

Step by Step Execution

Consider this code:

val colors = arrayOf("red", "green", "blue")
val wanted = "green"

val exists = wanted in colors
println(exists)

Execution:

  1. colors is created with three strings: red, green, and blue.
  2. wanted stores the string green.
  3. wanted in colors checks the array elements for one equal to wanted.
  4. red does not match green.
  5. green matches, so Kotlin can stop checking.
  6. exists receives true.
  7. The program prints true.

A conditional search works similarly:

val values = arrayOf("cat", "dog", "elephant")
val hasLongWord = values.any { it.length > 5 }

println(hasLongWord) // true

any tests cat, then dog, then elephant. The last string has more than five characters, so the result is true.

Real World Use Cases

Membership checks appear whenever an application needs to allow, deny, or recognize a known value.

  • User roles: check whether a user has an allowed role.
    val allowedRoles = arrayOf("admin", "moderator")
    val allowed = userRole in allowedRoles
    
  • File validation: allow only selected extensions.
    val allowedExtensions = arrayOf("jpg", "png", "webp")
    val valid = extension in allowedExtensions
    
  • API parameters: verify that a sort parameter is one of the supported values.
  • Command-line tools: check whether a supplied command is recognized.
  • Data cleaning: determine whether a status belongs to a list of values that should be skipped.
Take Quiz

Real Codebase Usage

In production Kotlin code, exact membership checks are commonly paired with validation and early returns.

fun parseSortOrder(input: String): String? {
    val supported = setOf("asc", "desc")

    if (input !in supported) {
        return null
    }

    return input
}

The !in operator means “is not contained in.” The early return prevents invalid values from reaching later logic.

For a fixed collection of unique allowed values, developers often use a Set:

private val allowedStatuses = setOf("pending", "active", "archived")

fun isAllowedStatus(status: String): Boolean = status in allowedStatuses

For custom rules, use any rather than trying to transform the collection first:

fun hasInternalEmail(emails: List<String>): Boolean {
    return emails.any { it.endsWith("@company.example") }
}

Use filter only when later code needs the matching elements:

val imageFiles = filenames.filter { it.endsWith(".png") }
println("Found ${imageFiles.size} PNG files")

Common Mistakes

Creating a filtered collection just to get a Boolean

This is valid but does extra work:

val found = array.filter { it == "value" }.any()

Prefer:

val found = "value" in array

Or, for a predicate:

val found = array.any { it == "value" }

Using === for string contents

=== checks whether two references point to the exact same object. It is usually wrong for comparing string text.

// Avoid for content comparison
val same = first === second

Use ==:

val same = first == second

Expecting case-insensitive matching by default

Membership is case-sensitive:

val values = arrayOf("Admin")
println("admin" in values) // false

For case-insensitive matching, use a predicate:

val exists = values.any { it.equals("admin", ignoreCase = true) }

Forgetting nullable values

An Array<String?> can contain null:

val values: Array<String?> = arrayOf("ready", null)
println(null in values) // true

Be explicit about whether null is a valid value in your application.

Checking the wrong collection type

Array, List, and Set all support in, but their performance characteristics differ. If you repeatedly look up values in a large unique collection, a Set is usually a better fit than an Array or List.

Comparisons

ApproachBest useResultNotes
value in arrayExact value membershipBooleanIdiomatic Kotlin syntax.
array.contains(value)Exact value membershipBooleanEquivalent to in; more explicit.
array.any { condition }Condition-based existence checkBooleanUse for rules such as prefixes, lengths, or case-insensitive comparisons.
array.filter { condition }You need all matching valuesList<T>Do not use only to determine whether a match exists.
set.contains(value)Frequent lookup in a unique-value collectionBooleanOften a better data structure for repeated membership checks.

in is not limited to arrays:

println("a" in listOf("a", "b")) // true
println("a" in setOf("a", "b"))  // true

For arrays and lists, searching is generally linear: elements are examined until a match is found or the collection ends. A hash-based set is generally more suitable for many repeated lookups.

Take Quiz

Cheat Sheet

// Exact match: recommended
val found = "value" in array

// Exact match: equivalent form
val found = array.contains("value")

// Not contained
val missing = "value" !in array

// Match a rule
val hasLongValue = array.any { it.length > 5 }

// Case-insensitive match
val foundIgnoringCase = array.any {
    it.equals("value", ignoreCase = true)
}

// Get every match, rather than only true/false
val matches = array.filter { it == "value" }

Rules to remember:

  • Use == for string content equality.
  • Use === only when reference identity is specifically required.
  • in and contains() are equivalent for membership checks.
  • Use any { ... } for a condition.
  • Avoid filter(...).any() unless you also need the filtered values.

FAQ

How do I check whether an array contains a string in Kotlin?

Use the in operator:

val exists = "value" in array

You can also write array.contains("value").

Is Kotlin in the same as contains()?

For membership checks, yes. value in collection calls the collection's containment logic and is commonly read as “value is contained in collection.”

Should I use filter().any() to check whether a value exists?

Usually no. It creates a filtered result before checking it. Use value in array for exact values, or array.any { ... } for a condition.

Does Kotlin compare strings by value?

Yes. first == second compares their text contents. Use === only when you need to know whether both variables refer to the same object.

How do I ignore uppercase and lowercase when checking strings?

Use any with equals:

val found = array.any { it.equals("value", ignoreCase = true) }

Can I use in with a Kotlin List or Set?

Yes. It works with Array, List, Set, and many other types that support containment.

When should I choose a Set instead of an Array?

Choose a Set when values are unique and your program performs many membership checks. It expresses that duplicates are not important and is commonly more efficient for lookup.

Take Quiz

Mini Project

Description

Build a small command validator for a console-style application. The program receives a command and reports whether it is supported. It demonstrates exact membership checks with in and a condition-based check with any.

Goal

Validate a command against a supported-command list and identify whether it is an administrative command.

Requirements

  1. Create a collection containing the commands help, list, create, and delete.
  2. Store a command to check in a variable.
  3. Print whether the command is supported.
  4. Print a separate message when the command is an administrative command.
  5. Treat create and delete as administrative commands.
Take Quiz

Keep learning

Related questions

View more