Reputation: 66
I have an array with (1, 2, null, 3...) and I want to create a for each loop to get only the values. I need this for many different aspects so it would be good if someone can show me a simple way to manage this.
I want that the 1, 2, 3 ... are in an array but without the null. I am a beginner and I don't find an answer of my question somewhere else.
Upvotes: 0
Views: 1071
Reputation: 19524
Kotlin puts a lot of emphasis on using functions to transform collections, instead of writing for
loops yourself. There are a lot of functions but two really important ones are map
and filter
.
map
transforms every element into something else - it maps each thing to another thing.
listOf(1, 2, 3).map { it * 2 }
>> [2, 4, 6]
filter
removes elements that don't match the predicate you pass in (a function that returns true for a match) - it keeps the ones that match, basically (you're filtering out the ones that don't)
listOf(1, 2, 3).filter { it > 1 }
>> [2, 3]
In this case, you want to filter out the null
values in your array. So you can do this:
arrayOf(1, 2, null, 3).filter { it != null }
>> [1, 2, 3]
so the filter is only allowing through things that aren't null, right?
There's a filterNot
function too, that flips the predicate logic - it only allows through things that don't match:
arrayOf(1, 2, null, 3).filterNot { it == null }
>> [1, 2, 3]
so now we're checking if each item is null, and only keeping it if that's not true. You can do it either way, whichever is more readable.
The main point is there's a special case for handling nulls - filterNotNull
which basically removes any null values:
arrayOf(1, 2, null, 3).filterNotNull()
>> [1, 2, 3]
There's also a mapNotNull
function which is a map
that also removes any nulls, which is sometimes handy.
An important thing about all these functions is they usually return a List
, so if you actually want an Array
you need to call toTypedArray()
at the end:
arrayOf(1, 2, null, 3).filterNotNull().toTypedArray()
but generally you work with lists a lot more in Kotlin, especially when working on collections.
Definitely worth reading through this to get familiar with things: Collections overview
There's a few sections on the left, but that's the stuff you need to know (even if you won't remember all of it!)
Upvotes: 2