Kotlin – Filter strings in list that contain specific substring

Kotlin – Filter strings in list that contain a specific substring

To filter strings in list that contain a specific substring in Kotlin, you can use List.filter() function with the predicate using String.contains() function.

The following is a step by step process to filter strings in a list that contain a specific substring in Kotlin.

  1. Consider that we are given a list of string values in words list.
  2. Call filter() function on the words list, and specify the predicate it.contains("substring"), where you need to replace the "substring" with the specific substring.
  3. The filter() function returns a new list with the string values from words list that satisfy the given predicate (condition).

Example 1: Filter strings in list that contain “rry” substring

In this example, we take a list of strings in words, and filter the string values in this list based on the condition that the string should contain the substring "rry".

Program

fun main() {
    val words = listOf("apple", "banana", "cherry", "date", "elderberry")

    val result = words.filter { it.contains("rry") }

    println(result)
}

Output

[cherry, elderberry]