Home » Kotlin filter list

Kotlin filter list

Kotlin filter list

1. Overview

In this article, we will discuss the various ways to filter the list in Kotlin.

2. Kotlin list filter example

Very often, you had to iterate a list and filter the elements based on certain conditions. Thus, Filtering a collection is one of the most basic and familiar tasks in programming history.

Kotlin provides the following functions to filter your list:

  • filter
  • filterIndexed
  • partition
  • filterIsInstance
  • filterNotNull

All the above functions take a predicate as the parameter. A predicate is a lambda that takes each list element and checks whether it satisfies the required condition. Thus, it returns a true or false value.

The filter function returns a single list as output with elements matching the required condition, whereas the partition function returns two list items: one with elements that match the condition and another with remaining list elements.

Now let’s see each of these functions.

2. Kotlin Filter function for list

The filter function is a basic filtering function. When you call the filter function with a predicate, it returns the list elements that match it. Therefore, the output of the function is also a list.

2.1. Kotlin Filter list of objects

For example, the below code has a list of Student objects. For example, you need to filter the student object whose name starts with the letter “A”.

Thus, you can use the filter function and pass the predicate to it. The predicate will take each of the list elements as input and use the startsWith function to check whether the student name starts with “A”.

fun main() {
    val asha = Student(101, "Asha")
    val john = Student(102, "John")
    val afra = Student(103, "Afra")
    val kyle = Student(104, "Kyle")
    val studentList = listOf(asha, john, afra, kyle)
    val filteredList = studentList.filter { student -> 
    			student.name.startsWith("A")
	}
    println(filteredList) /* prints [Student(id=101, name=Asha), Student(id=103, name=Afra)] */
}

data class Student(val id: Long, val name: String)

3. Kotlin filterNot function for list

The filterNot function returns the list elements that do not match the provided condition.

For example, the below code uses the filterNot function to filter the students whose name doesn’t start with K.

fun main() {
    val asha = Student(101, "Asha")
    val john = Student(102, "John")
    val afra = Student(103, "Afra")
    val kyle = Student(104, "Kyle")
    val studentList = listOf(asha, john, afra, kyle)
    val filteredList = studentList.filterNot { student -> 
    			student.name.startsWith("K")
	}
    println(filteredList) /* prints [Student(id=101, name=Asha), Student(id=102, name=John), Student(id=103, name=Afra)]*/
}

data class Student(val id: Long, val name: String)

4. Kotlin filter null values from the list using filterNotNull function

The filterNotNull function returns all non-null elements in the list. So you can use this function to eliminate the null values from a list.

For example, the below code has a list containing students. The list also has null values. So you can use filterNotNull function to remove the null values from this student list and get a list of non-null student objects.

fun main() {
    val asha = Student(101, "Asha")
    val afra = Student(103, "Afra")
    val studentList = listOf(asha, null, afra, null)
    val filteredList = studentList.filterNotNull().forEach {  
    		println(it) 
/* prints Student(id=101, name=Asha)
Student(id=103, name=Afra) */
	}
}

data class Student(val id: Long, val name: String)

5. Kotlin filterIndexed example

So far, we have discussed filtering based on elements. Assume you want to filter based on element index.

This filterIndexed function takes a predicate with two parameters: index and list element. Using this, you can filter based on the index as well.

In the below code, we are using the filterIndexed function to filter all the list elements at an even position.

fun main() {
    val numbers = listOf("zero", "one", "two", "three", "four")
    val filteredIdx = numbers.filterIndexed { index, s -> (index % 2 == 0) }
    println(filteredIdx) /* prints [zero, two, four] */
}

data class Student(val id: Long, val name: String)

4. Kotlin filterIsInstance function

You can use filterIsInstance function to return the list element that matches the provided type.

Assume you have a list of varying types such as String, Int, Float, so on, and you had to filter only string elements from that list.

You can use filterIsInstance and pass the type as String as below. You can also apply any String functions to the elements.

fun main() {
    val numbers = listOf(null, 1, "two", 3.0, "four")

	numbers.filterIsInstance<String>().forEach {
    	println(it.uppercase())
	}
}

6. Kotlin split list by predicate

You can use partition function to split the list by predicate. This partition function will keep the elements that don’t match the condition in a separate list.

The output would be a Pair of List: the first one containing elements that match the required condition and the next one containing the remaining list elements.

Assume you have a list of student objects and you want to filter the students who studying in the IT department separately from other departments. Thus, you can use this function to achieve it.

fun main() {
    val asha = Student(101, "Asha", "IT")
    val john = Student(102, "John", "Mechanic")
    val afra = Student(103, "Afra", "Bio")
    val kyle = Student(104, "Kyle", "IT")
    val studentList = listOf(asha, john, afra, kyle)

	val (itDept, others) = studentList.partition {
    	student -> student.dept.equals("IT")
	}
    println(itDept)
    println(others)
/* prints 
[Student(id=101, name=Asha, dept=IT), Student(id=104, name=Kyle, dept=IT)]
[Student(id=102, name=John, dept=Mechanic), Student(id=103, name=Afra, dept=Bio)] */
}

data class Student(val id: Long, val name: String, val dept: String)

7. Kotlin filter arraylist

Similarly, you can use the filter function to get the array elements that match a certain condition.

The below code matches String “three” in the list and returns a list.

fun main() {
    val numbers = arrayListOf("zero", "one", "two", "three", "four")
	println(numbers.filter { it -> it.equals("three") }) /* prints [three] */
}

However, you can call the single function on the list to get the String instead of a list.

fun main() {
    val numbers = arrayListOf("zero", "one", "two", "three", "four")
	println(numbers.filter { it -> it.contains("ee") }.single()) /* prints three */
}

8. Conclusion

To sum up, this article explained the standard Kotlin functions available to filter the list based on certain conditions. See our Kotlin filter map article to filter the map.

Leave a Reply

Your email address will not be published. Required fields are marked *