Kotlin – Filter strings in a list based on a condition

Kotlin – Filter strings in a list based on a condition

To filter strings in a list based on a condition in Kotlin, you can use List.filter() function.

The following is a step by step process to filter strings in a list based on a condition 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 to filter. The predicate is the condition. The string values in the list that satisfy the given predicate are returned in the resulting list by filter() function.
  3. Therefore, 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 whose length is greater than 5

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 length is greater than 5.

Program

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

    val result = words.filter { it.length > 5 }

    println(result)
}

Output

[banana, cherry, elderberry]

Example 2: Filter non-empty strings in list

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 is not an empty string.

Program

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

    val result = words.filter { it.length > 0 }

    println(result)
}

Output

[apple, banana, cherry, elderberry]

Example 3: Filter strings in list that contain the substring ‘rry’

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]