简体   繁体   中英

Iterate through list and handle not found items in Scala

I have two lists A and B. I want to iterate through list B and find matches from A. For every non-match I would like to call another function to compute a new value.

I tried different ways to get to the wanted result:

val a = List(1,2,3)
val b = List(1,2,4,5)
def compute(i:Int):Int = -1*i
// What I want: val r = List(1,2,-4,-5)
val r1 = b.foreach(bb => a.find(aa => aa==bb).getOrElse(compute(bb)))
val r2 = for {
 bb <- b
 r <- a.find(_ == bb).getOrElse(compute(bb))
} yield r

In reality my lists are some more complex, but this simple example works.

Obviously I'm missing something here and might even be attacking it the wrong way. I hope someone can point me in the right direction. Thanks.

Maybe make a into set and then map.

val s = a.toSet
b.map{e => if (s.contains(e)) compute(e) else e}
val r = b map (elem => if (a contains elem) elem else compute(elem))

How about this?

b.map(i => {
  val matches = a.filter(x => x == i)
  if (matches.nonEmpty) matches.head
  else compute(i)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM