Kotlin filter two lists

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[].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.

To filter elements in a Kotlin List based on a predicate [condition], call filter[] function on this List and pass the predicate to the filter[] function as parameter.

In this tutorial, we will learn how to use filter[] function on a List, to filter its elements based on a condition/predicate.

The syntax to call filter[] function on a List with a predicate is

List.filter[predicate]

predicate is a lambda function that takes an element of the List as parameter and returns a boolean value.

Return Value

List.filter[] function returns a List.

Elements of the List that return true for the given predicate, make it to the filtered List.

The original list on which filter[] function is called, remains unchanged. Therefore, we can fall filter[] function on a List, or a Mutable List.

Examples

In the following program, we will take a List of Integers and filter only even numbers.

Main.kt

fun main[args: Array] { var myList = listOf[1, 4, 8, 5, 6, 9, 12, 10, 33] var filteredList = myList.filter { x -> x % 2 == 0 } println["Original List : ${myList}"] println["Filtered List : ${filteredList}"] }

Here, the lambda function: { x -> x % 2 == 0 } is the predicate to the filter[] function.

For each element x in the List, only those elements that satisfy the condition x % 2 == 0 are returned in the resulting List.

Output

Original List : [1, 4, 8, 5, 6, 9, 12, 10, 33] Filtered List : [4, 8, 6, 12, 10]

In the following example, we will take a list of Strings, and filter only those strings whose length is greater than 2.

Main.kt

fun main[args: Array] { var myList = listOf["This", "is", "a", "test"] var filteredList = myList.filter { x -> x.length > 2 } println["Original List : ${myList}"] println["Filtered List : ${filteredList}"] }

Output

Original List : [This, is, a, test] Filtered List : [This, test]

Conclusion

In this Kotlin Tutorial, we learned how to filter a List using a condition/predicate, using filter[] function, with the help of examples.

➥ PDF Download - How to Filter Elements of a List based on Condition in Kotlin?

Video liên quan

Chủ Đề