Back to Blog

Kotlin: Find the occurrence of a string in a list

Sandy LaneSandy Lane

Video: Kotlin: Find the occurrence of a string in a list by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin: Find the Occurrence of a String in a List

In Kotlin, you can easily find how many times a specific string appears in a list using built-in collection functions. This is useful for counting occurrences or checking if a string exists multiple times within a list of strings.

Code

fun main() {
  val fruits = listOf("apple", "banana", "apple", "orange", "banana", "apple")

  // The string to find
  val target = "apple"

  // Count how many times 'target' appears in the list
  val count = fruits.count { it == target }

  println("The string '$target' appears $count times in the list.")
}

Key Points

  • The count function with a predicate counts matching elements in a list.
  • You can use a lambda expression to specify the condition for counting.
  • This approach works for any list and any type, not just strings.
  • Using count is more concise and idiomatic than manually iterating and counting.