Kotlin Tip #43: Use listOfNotNull for filtering null values from collections — 100 Kotlin Tips in 100 Days
Twitter | LinkedIn | YouTube | Instagram
Tip #42: Usefold
andreduce
for Aggregating Collection Values
When working with collections in Kotlin, it’s not uncommon to end up with a list that contains null elements, either as a result of transformations, computations, or external data sources.
Manually checking each element for nullity can be cumbersome and error-prone. Kotlin’s listOfNotNull
function simplifies this task by automatically filtering out null values and returning a new list containing only the non-null elements.
The listOfNotNull
function is straightforward to use. It can be applied directly to a collection or used as a standalone function to create a new list from a set of potentially nullable elements.
Here’s a basic example of using listOfNotNull
with a collection:
And here’s how you can use listOfNotNull
to create a new list while filtering out null values:
Imagine you’re getting user data from a database, and because some fields are optional or some records aren’t complete, you might end up with a list that has null entries.
By using “listOfNotNull,” you can quickly remove any null values from the list. This makes sure that when you work on the list later, you won’t run into problems because of unexpected nulls.
By using this function in your Kotlin projects, you can manage collections better, making sure your work with these collections doesn’t run into problems because of nulls.
I hope you have enjoyed this tip of our series! Don’t forget to subscribe and stay tuned for more Kotlin tips!
Stay curious!
Tip #44: Implement collection plus and minus operators for adding or removing elements
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.