Frankie Guzikowski
Frankie Guzikowski

Reputation: 35

Empty check in lambda mapping to avoid indexOutOfBounds

I want to map time values of arrayList dictionary keys to a list using a lambda map expression. I have it working with double for loop to show the logic clearly without leveraging the Kotlin way.

I have the lambda mapping correctly once each arrayList has at least one element, the only built in function I see that is close is .filter but this needs to be done before checking the index to avoid exception throwing

Map (eventData[0] is where time goes)

var videoFileMap = mutableMapOf(Types.A to arrayListOf<EventData>(),
          Types.B to arrayListOf(),
               Types.C to arrayListOf(),
                    Types.D to arrayListOf())

For loop:

for (videoFileList in videoFileMap) {
  for (videoFileData in videoFileList.value) {
    timeValues[i] = videoFileData.time - System.currentTimeMillis()
  }
}

lambda without checking (throws indexoutofbounds exception):

timeValues = videoFileMap.values.map{ it[0].time - System.currentTimeMillis() }

and trying to check size (required ArrayList, received Comparable(Double & Int) and Number)

timeValues = videoFileMap.values.map{ if (it.size>0) {
   it[0].time - System.currentTimeMillis() 
   } else {-1} }

thanks in advance for the functional help!

Upvotes: 0

Views: 138

Answers (1)

Andrei Tanana
Andrei Tanana

Reputation: 8422

How about this?

val timeValues = videoFileMap.values.mapNotNull { it.firstOrNull() }
        .map { it.time - System.currentTimeMillis() }

Upvotes: 0

Related Questions