C N
C N

Reputation: 13

Scala: Swapping two key values in a collection?

I have a val pointing to a big collection of records that were read from a file in HDFS. Let's call this val 'a'. 'a' has a bunch of records that all contain these 3 properties: SRC, DEST, ACT. I need to make a clone of 'a', but have the values of SRC and DEST keys swapped in each record. How do I go about doing this in scala? I've tried different variants of the map function but can't seem to get this to work correctly.

Upvotes: 0

Views: 122

Answers (1)

EmilioMg
EmilioMg

Reputation: 376

Well, without a code example, I am guessing at your needs and prerequisites, but something like this could work:

case class Record(src: String, dest: String, act: String)

val a = List(
    Record("srcA", "destA", "actA"),
    Record("srcB", "destB", "actB"),
    Record("srcC", "destC", "actC"),
    Record("srcD", "destD", "actD"),
    Record("srcE", "destE", "actE"),
)

val b = a.map(r => Record(r.dest, r.src, r.act))

println(a)
// => List(Record(srcA,destA,actA), Record(srcB,destB,actB), Record(srcC,destC,actC), Record(srcD,destD,actD), Record(srcE,destE,actE))

println(b)
// => List(Record(destA,srcA,actA), Record(destB,srcB,actB), Record(destC,srcC,actC), Record(destD,srcD,actD), Record(destE,srcE,actE))

Upvotes: 2

Related Questions