scalacode
scalacode

Reputation: 1106

chaage value of Map scala based in key

I have the following :

 val dynamoItem = rowAsMap.mapValues {
  v: Any => new AttributeValue().withS(v.toString)
}.asJava

I want to change the mapValues function and make it apply the appropriate function to value based on the Key

So if the Key is equal to "AER" I want it to do : v: Any => new AttributeValue().withN(v.toString)

and for other values of Key I wanted to make

 v: Any => new AttributeValue().withS(v.toString)

Upvotes: 0

Views: 46

Answers (2)

Terry Dactyl
Terry Dactyl

Reputation: 1868

I would avoid the x._n notation to access tuple elements wherever possible. This is essentially the same answer provided above but I find this more readable.

val dynamoItem = rowAsMap.map { 
  case("AER", value) => "AER" -> new AttributeValue().withN(value.toString)
  case (key, value) => key -> new AttributeValue().withS(value.toString)
}

Note - I assume you are preserving keys and replacing values with new AttributeValue().withN(value.toString) or new AttributeValue().withS(value.toString)

Upvotes: 2

AlleXyS
AlleXyS

Reputation: 2598

If I understand, you want to transform rowAsMap values (which are Map() values).

val dynamoItem = rowAsMap.map { item =>
  if (item._1 == "AER") 
     new AttributeValue().withN(item._2.toString)
  else 
     new AttributeValue().withS(item._2.toString)
}

Upvotes: 1

Related Questions