Home > Software design >  Fill missing data in a linear model
Fill missing data in a linear model

Time:05-17

I have the following val list = listOf(1, 2, 3, null, null, 6, 7) I'd like to fill the null value for the following result: listOf(1, 2, 3, 4, 5, 6, 7)

I couldn't find any method doing this in Kotlin, do you guys have an idea?

EDIT: I'm adding more details, the list will always have a beginning element and an ending element (ie no list as listOf(null, 2 ,3) or listOf(1, 2, null)) I preprocess this.

In my example I gave Integer element but it could be Float or Double

CodePudding user response:

It's no idea to decide what number you what to replace with null.

Considing what if listOf(1, null, null) or listOf(null, 2, null).

If you know exactly what a list needs to be, you mignt use IntProgression or IntRange instead.

// 1, 2, 3, 4, 5, 6, 7
val list1 = IntRange(1, 7).toList()

// 1, 3, 5, 7
val list1 = IntProgression(1, 7, 2).toList()

CodePudding user response:

Try this

inline fun <T>List<T?>.replaceIfNull(block:(T) -> T) : List<T>{
    val temp = mutableListOf<T>()
    for((index, element) in this.withIndex()){
        if(element == null){
            temp.add(block(this[index - 1] ?: temp[index - 1]))
        } else {
            temp.add(element)
        }
    }
    return temp
}


fun main() {
   val list = listOf(1, 2, 3, null, null, 6, 7) 
   val foo = list.replaceIfNull { nonNullValue ->
       nonNullValue   1
   }
   println(foo) // [1, 2, 3, 4, 5, 6, 7]
}

test: https://pl.kotl.in/65yVIXkrj

  • Related