Filtering out non null values from a collection in kotlin

kotlin map filter null values
kotlin filter
kotlin filter not null property
kotlin filter multiple conditions
kotlin filter map example
kotlin filter on empty list
kotlin mapnotnull
filterindexed kotlin

Take a look at this kotlin one liner:

val nonNullArr : List<NonNullType> = nullArray.filter {it != null}

The compiler gives a type error at this line, saying that a list of nullables can't be assigned to a list of non-nulls. But the filter conditional makes sure that the list will only contain non null values. Is there something similar to !! operator that I can use in this situation to make this code compile?

It seems logical to assume that the compiler would take into account the predicate

it != null

and infer the type as

List<NonNullType>

but it does not. There are 2 solutions:

val nonNullList: List<NonNullType>  = nullableArray.filterNotNull()

or

val nonNullList: List<NonNullType>  = nullableArray.mapNotNull { it }

filterNotNull, fun <T : Any> Array<out T?>.filterNotNull(): List<T>. fun <T : Any> Iterable<T?>. filterNotNull(): List<T>. Returns a list containing all elements that are not null . We often need to work with collections in our Kotlin code, and on many occasions, we need to be able to transform either the elements of the collection or the entire collection into other forms. The Kotlin standard library gives us a number of built-in ways to achieve this so that we can better focus on our code. 2. Filtering Values

As far as I know, you cannot convert nullable types into nonNull types by just verifying that they are not null. To achieve what you want, you need to manually map nullable values to non-null type by simply creating NonNull type object. For this you can use map extension function.

val nullableArray: Array<String?> = arrayOf("abc", "xyz", null, "efg")

val nonNullList: List<String> = nullableArray.filter { it != null }.map {
    it.toString()
}

Or you can use filterNotNull() method as @forpas suggested in comments

val nonNullList: List<String>  = nullableArray.filterNotNull()

Hope it helps you!

Filter non null elements - Libraries, Lets say I have a list of Int and null values, so that the type of the list is List<Int?>. Now I want to filter all elements being not null. Int?> but kotlin.collections. Kotlin Null Safety. Kotlin compiler by default doesn’t allow any types to have a value of null at compile-time. For Kotlin, Nullability is a type.At a higher level, a Kotlin type fits in either of the two.

You can't assign a nullable type to a non-nullable type of value. The type-matching maybe works when you assign a value, not after filter operation called.

// the type-matching works before `.filter` is called
val nonNullArr : List<NonNullType> = nullArray//.filter {it != null} 

instead, if you want to do this without an error or without concerning the type. Remove the type from the val, so it goes like this

val nonNullArr = nullArray.filter {it != null} 

Hope it helps

Filtering Collections, To operate the filtering result, you should assign it to a variable or chain the returns a List<T: Any> , thus allowing you to treat the elements as non-null objects. import kotlin.test.* fun main(args: Array<String>) { //sampleStart val numbers: List<Int?> = listOf(1, 2, null, 4) val nonNullNumbers = numbers.filterNotNull

listOfNotNull, Returns a new read-only list either of single given element, if it is not null, or empty list if the element is null. The returned list is serializable (JVM). Null Safety Nullable types and Non-Null Types. Kotlin's type system is aimed at eliminating the danger of null references from code, also known as the The Billion Dollar Mistake. One of the most common pitfalls in many programming languages, including Java, is that accessing a member of a null reference will result in a null reference exception.

mapNotNull, Returns a list containing only the non-null results of applying the given transform function to each element in the original collection. Common. JVM. JS. Native. 1.0. A generic collection of elements. Methods in this interface support only read-only access to the collection; read/write access is supported through the MutableCollection interface. Parameters. E - the type of elements contained in the collection. The collection is covariant on its element type.

Filtering Kotlin Collections, A quick and practical reference for filtering Kotlin collections. The method stops removing elements as soon as an element does not meet the to determine whether to return a null value or not – think Optional#filter. Groups values returned by the valueTransform function applied to each element of the original collection by the key returned by the given keySelector function applied to the element and returns a map where each group key is associated with a list of corresponding values.

Comments
  • Use nullArray.filterNotNull() instead.
  • what if List has no-null objects but i want to filter based on some key of that object whose value is null. How about doing that ?
  • @zero first map the list to the key, then filter not null and filter original list according to result equality.