In this article , lets discuss about Kotlin Collections operation - Filter functions
Filtering a collection is an everyday task in dev life. In Kotlin , Filtering conditions are defined by predicates
predicate
takes a collection value and returns a
boolean
valueif it returns
true
-> given element matches predicateif it returns
false
-> given element not matches predicate
Filter by predicate
filter()
when called with predicate ,
filter()
returns the list of elements that matches the conditionFor both
List
andSet
, the result isList
For
Map
, the result isMap
val numbers = listOf(62, 51, 67, 32, 45, 12)
//filter for list and set
val result = numbers.filter { it > 50 }
println(result)
//output: [62, 51, 67]
val studentInfo = mapOf(
"Student 1" to 18,
"Student 99" to 19,
"Student 101" to 21,
"Student 199" to 23
)
//filter for map
val seniorStudent = studentInfo.filter { (student, age) ->
student.endsWith("9") && age > 20
}
println(seniorStudent)
//output: {Student 199=23}
filterIndexed()
If we need the element position in filter we can use
filterIndexed()
It takes the predicate with two arguments : index and value
val numbers = listOf(62, 51, 67, 32, 45, 12)
// filer indexed
val filterIndexedResult = numbers.filterIndexed { index, i ->
index != 0 && i > 60
}
println(filterIndexedResult)
//output : [67]
filterNot()
filter collections by negative conditions
returns the list of all elements that predicate returned false
val numbers = listOf(62, 51, 67, 32, 45, 12)
//filterNot
val filterNotResult = numbers.filterNot {
it > 50
}
println(filterNotResult)
//output : [32, 45, 12]
filterIsInstance()
returns the collection of given type
if we call on
List<Any>
withfilterIsInstance<String>()
, the result is list of strings i.eList<String>
val typesList = listOf(1, null, "one", 'f', 3, null, 4.56, 78.9087, "twenty")
//filterIsInstance
val filterInstanceResult = typesList.filterIsInstance<Double>()
println(filterInstanceResult)
//output : [4.56, 78.9087]
filterNotNull()
returns all non-nullable elements in the collection
if we call on
List<T>
, it returnsList<T : Any>
val typesList = listOf(1, null, "one", 'f', 3, null, 4.56, 78.9087, "twenty")
// filterNotNull
val filterNotNullResult = typesList.filterNotNull()
println(filterNotNullResult)
//output: [1, one, f, 3, 4.56, 78.9087, twenty]
Partition
partition()
filters the given collection by predicate and keeps the elements that does not match in a separate list
returns pair of list , first one containing the elements matching the predicate and the second one not matching the predicate
val numbers = listOf(23, 56, 34, 67, 12, 73, 8, 82, 45, 90)
val partition = numbers.partition {
it > 50
}
println(partition.first)
//output : [56, 67, 73, 82, 90]
println(partition.second)
//output : [23, 34, 12, 8, 45]
Please leave your comments to improve.
Happy and Enjoy coding