Garipaso
Garipaso

Reputation: 421

update keys in scala

I have to update keys in a map based on certain condition. values will not be modified.

I have ended up with this code, but doesn't look neat to me, is there any better alternative of doing this:

val newOpt =  inOpt("type") match {

  case "mydb" =>
    inOpt map { case (key, value) => (

      if (key.contains(XXXX)) {
        key.replace("A", "B")
      }
      else if(...){..}
      else {
        key
      }


      , value)
    }
}

All the updated keys along with old keys and values will be in newOpt.

Regards

Upvotes: 2

Views: 4134

Answers (3)

echo
echo

Reputation: 1291

For

val m = Seq((1,2),(11,22)).toMap
m: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 11 -> 22)

create a new map based in m with updated,

val m2 = m.updated(11,23)
m2: scala.collection.immutable.Map[Int,Int] = Map(1 -> 2, 11 -> 23)

Upvotes: 1

prayagupadhyay
prayagupadhyay

Reputation: 31212

At least you can separate the updateKey logic to a different function, also you might use pattern matching for if else.

val newMap = originalMap map { case (key, value) => (updatedKey(key), value)}

At least it might look cleaner but not necessarily better solution than yours.

class UpdateKeysSpecs extends FunSuite {

  test("updates the keys") {
    val originalMap : Map[String, String]= Map("key1" -> "value1", 
      "key2_old" -> "value2", 
      "key3_something" -> "value3")

    val newMap = originalMap map { case (key, value) => (updatedKey(key), value)}

    assert(newMap.keys == Set("key1", "key2_new", "key3_nothing"))
  }

  def updatedKey(key: String): String = {
    key.contains("old") match {
      case true => key.replace("old", "new")
      case false => {
        key.contains("something") match {
          case true => key.replace("something", "nothing")
          case false => key
        }
      }
    }
  }
}

Upvotes: 3

Dhirendra
Dhirendra

Reputation: 309

try this

val m = Map(1->"hi",2->"Bye")
scala.collection.immutable.Map[Int,String] = Map(1 -> hi, 2 -> Bye)

Update the key 2 with 5

m.map{x=> if(x._1 == 2) (5 -> x._2) else x}
scala.collection.immutable.Map[Int,String] = Map(1 -> hi, 5 -> Bye)

Upvotes: 7

Related Questions