Kotlin Tip #36: Use filter and filterNot to Collection filtering — 100 Kotlin Tips in 100 Days
Twitter | LinkedIn | YouTube | Instagram
Tip #35: Use Tailrec for Efficient Recursion
When working with collections in Kotlin, it’s often necessary to sift through the elements to find those that meet certain criteria. Whether you’re dealing with lists, sets, or any other collection types, Kotlin provides two powerful functions to streamline this process: filter
and filterNot
.
The filter
function allows you to specify a condition (a predicate) and returns a new collection containing only the elements that satisfy this condition. On the other hand, filterNot
does the opposite: it returns a collection of elements that do not match the given condition. Both functions are available for all types of collections.
Consider you have a list of integers and you want to extract only the even numbers. The filter
function makes this task straightforward:
The lambda expression { it % 2 == 0 }
serves as the predicate, instructing filter
to include only those elements (it
) which, when divided by 2, produce no remainder.
Now, if you wish to obtain the odd numbers from the same list, filterNot
comes into play:
Here, filterNot
excludes elements that meet the condition, collecting the odd numbers in the list.
Filtering capabilities shine in more complex scenarios, such as processing collections of objects. Imagine you have a list of Person
objects and you need to find those who are eligible for a certain service based on age:
This code snippet demonstrates how filter
can be used to sift through a collection based on object properties, making the code not only more readable but also expressive.
I hope you have enjoyed this tip of our series! Don’t forget to subscribe and stay tuned for more Kotlin tips!
Stay curious!
Contribute
Writing takes time and effort. I love writing and sharing knowledge, but I also have bills to pay. If you like my work, please, consider donating through Buy Me a Coffee: https://www.buymeacoffee.com/RaphaelDeLio
Or by sending me BitCoin: 1HjG7pmghg3Z8RATH4aiUWr156BGafJ6Zw
Follow Me on Social Media
Stay connected and dive deeper into the world of Kotlin with me! Follow my journey across all major social platforms for exclusive content, tips, and discussions.