Kotlin | Filtering Collections
In Kotlin, filtering is a prominent task of collection processing. The filtering conditions are defined by predicates – lambda functions that take a collection element and return true when the given element matches the predicate, and false means it doesn’t match the predicate.
- There are standard library contains number of functions that let you filter the collections in a single call.
- These functions don’t change the contents of the original collection or available for immutable and mutable both.
- We can assign it to a variable or chain the functions after filtering to operate the filtering result.
Filtering by predicates –
- The basic function is filter() to be used for filtering.
- When filter() function is called with a predicate, it returns the collection elements that match the predicate.
- For List and Set, the resulting collection is also List but for Map it will return Map.
Kotlin program of using the filter function on list and Map collection –
Java
fun main(args: Array<String>)
{
val list = listOf("geeks"," for ","geeks","hello","world")
val longerThan4 = list.filter { it.length > 4 }
println(longerThan4)
val numbersMap = mapOf("key13" to 10 , "key25" to 20 ,
"key34" to 30 , "key45" to 40 , "key55" to 50 )
val filteredMap = numbersMap.filter { (key, value) ->
key.endsWith(" 5 ") && value > 20 }
println(filteredMap)
}
|
Output:
[geeks, geeks, hello, world]
{key45=40, key55=50}
Variations in filter()
- If we want to filter using element index or position, we have to use filterIndexed().
- filterIndexed() function takes a predicate with two arguments: index and the value of an element.
- We can filter the collections by negative conditions by using filterNot().
Kotlin program of using the filterIndexed() and filterNot() functions –
Java
fun main(args: Array<String>) {
val words = listOf("geek"," for ","geeks","all","world")
val filteredIndex = words.filterIndexed { index, s ->
(index != 0 ) && (s.length < 6 ) }
val filteredNot = words.filterNot { it.length <= 3 }
println(filteredIndex)
println(filteredNot)
}
|
Output:
[for, geeks, all, world]
[geek, geeks, world]
Partitioning –
There is another filtering function partition() which filters a collection by a predicate and separates all the elements, which don’t match the predicate and put in a different list.
Basically, it returns a pair of list: the first list containing the elements that match the predicate and the second list contains all the element from the original collection which don’t match the predicate.
Kotlin program of using partitioning –
Java
fun main(args: Array<String>) {
val words = listOf("geek"," for ","geeks","hello","world")
val (first, second) = words.partition { it.length > 4 }
println(first)
println(second)
}
|
Output:
[geeks, hello, world]
[geek, for]
Testing predicates –
Some of the functions to test a predicate against the collection elements are following:
- any() : It returns true if atleast one element matches the given predicate.
- none() : It returns true if none of the elements match the given predicate.
- all() : It returns true if all the elements of the collection match the given predicate.
Note: all() returns true when called with any valid predicate on an empty collection. This is known as vacuous truth.
We can use any() and none() without a predicate, it will just check for the emptiness of the collection, i.e. any() will return true if collection has elements and false if its empty; none() do just opposite of any().
Kotlin program of using any(), none() and all() functions –
Java
fun main(args: Array<String>) {
val words = listOf("geeks"," for ","geeeks","hello","world")
println("Any element matches? "+words.any { it.endsWith("s") })
println("No element matches? "+words.none { it.endsWith("a") })
println("All element match? "+words.all { it.endsWith("d") })
println(words.any())
println(words.none())
println(emptyList<Int>().all { it > 5 })
val empty = emptyList<String>()
println(empty.any())
println(empty.none())
}
|
Output:
Any element matches? true
No element matches? true
All element match? false
true
false
true
false
true
Last Updated :
21 Feb, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...