Home > Back-end >  Scala concatenate Map - one with Option and other without Option
Scala concatenate Map - one with Option and other without Option

Time:04-05

I have the below input values

import java.sql.Timestamp
import java.lang.{Double => JDouble}
val date = Timestamp.valueOf("2021-08-01 00:00:00")
 val contractRate: Map[String, JDouble] = Map("ITABUS" -> 0.075,
    "KARAT-S" -> 0.10,
    "KAUTRA" -> 0.05)
  val timeBoundContractRatesList: Map[String, List[(Timestamp, JDouble)]] = Map(
    "ITABUS" -> List((Timestamp.valueOf("2021-07-30 23:59:59"), 0.085.asInstanceOf[JDouble]),
    )
  )

My requirement here is:

  1. There are 2 types of rates. One is fixed rate and other is time bound rate

  2. I need to apply the time bound rate if the date is greater than today (for example)

  3. I am trying with the approach to have a single consolidated Map like below

    val withTimeBoundContractRate = contractRate    timeBoundContractRatesList
       .map { case (carrier, timeRateSet) =>
         val filteredEntry = timeRateSet
           .filter { case (startDate, _) => date.after(startDate) }
         (carrier, filteredEntry.map(_._2).headOption)
       }
       .filter(_._2.nonEmpty)
    

The problem is with the output. I get the below output

withTimeBoundContractRate: scala.collection.immutable.Map[String,java.io.Serializable] = Map(ITABUS -> Some(0.085), KARAT-S -> 0.1, KAUTRA -> 0.05)

But what I am looking for is a Map with original datatype(without Option)

withTimeBoundContractRate: Map[String, JDouble] = Map(ITABUS -> 0.085, KARAT-S -> 0.1, KAUTRA -> 0.05)

Or is there a totally different approach to solve this efficiently?

CodePudding user response:

(I think, I misunderstood what you are trying to do originally, so I deleted by first answer, to replace it with this):

You actually almost have it, the only problem is that the values in your second map are Options. Just "unwrap" them:

contractRate    timeBoundContractRatesList.mapValues { 
  _.find(date.after(_._1)).map(_._2)
}.collect { case(k, Some(v)) => k -> v }

The main difference from your snippet here is to use collect instead of filter: it lets you not only remove the empty values, but also transform the non-empty ones to get rid of the Option around them.

  • Related