Skip to content
DeveloperMemos

Filtering Lists in Kotlin using filter

Kotlin, Lists, Filter1 min read

In Kotlin, it is possible to filter a list of items using the filter function. This function takes a predicate as an argument, which is a function that returns a Boolean value indicating whether an element should be included in the filtered list or not. In this article, we will look at a few examples of how to use the filter function to filter a list in Kotlin.

First, let's create a list of integers that we will use in our examples:

1val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

To filter this list, we can use the filter function and pass in a predicate that checks if an element is greater than a certain value. For example, to get all elements that are greater than 5, we can use the following code:

1val greaterThanFive = numbers.filter { it > 5 }

In this example, the greaterThanFive variable will contain a list of all elements in the numbers list that are greater than 5.

We can also use the filter function to filter a list of objects. For example, let's say we have a Person class that has a name and an age property:

1data class Person(val name: String, val age: Int)

We can create a list of Person objects and use the filter function to get all objects that have an age greater than 30:

1val people = listOf(
2 Person("John", 25),
3 Person("Jane", 30),
4 Person("Bob", 35),
5 Person("Sue", 40)
6)
7
8val overThirty = people.filter { it.age > 30 }

In this example, the overThirty variable will contain a list of all Person objects in the people list that have an age greater than 30.

In conclusion, the filter function in Kotlin is a powerful tool for filtering a list of items. It allows us to specify a predicate that determines which elements should be included in the filtered list. This can be useful for many different scenarios, including working with lists of numbers, objects, or any other type of data.