繁体   English   中英

如何迭代scala中的集合Future并修改现有的记录/变量?

[英]How to iterate over a collection Future in scala and modify an existing record/variable?

这是我想要实现的简化示例。 我基本上有一个字符串,我需要根据Future字符串列表中的元素进行修改。 以下是我想要实现的一个简短示例。

import scala.concurrent.Future
import scala.util.matching.Regex

object FutureEx01 extends App
{

  var myString = "what the fcuk is happening here"
  val myList: Future[List[String]] = Future { List("fcuk", "shit", "motherfcuker", "ahole") }

  // TODO: iterate over myList, look at the elements and if there is a match with any word in myString, replace it.

/**

//this is what I could think of!  

  myList.map({

    listEle: String =>
      val listEleRegex: Regex = listEle.r
      myString = listEleRegex.replaceAllIn(myString,"CENSORED")
  })
*/
}

所以我想替换我的字符串中的所有不良单词。 你能帮我解决一下怎么回事吗?

谢谢

我认为这就是你所需要的。

val goodString = myList.map{ bads =>
                   myString.replaceAll(bads.mkString("|"), "CENSORED")
                 }

结果是类型Future[String] ,它将在myList完成时完成。

  1. 不要使用可变状态( foldLeft是你想要的)。
  2. 我不确定为什么你的myList thingy是Future ,但是假设,这就是你真正想要的,你需要在map使用foldLeft

     val futureResult: Future[String] = myList.map { exclude => exclude .foldLeft(myString) { case(str, ex) => ex.r.replaceAllIn(str, "CENSORED") } } 

现在你可以做val result = Await.result(futureResult)futureResult.onComplete(println)等等。

首先,您必须将字符串拆分为数组:

val splitted = myString.split(" ")

然后你可以映射未​​来:

val future = myList.map(splitted.diff(_))

这将带来结果的未来。 要提取最终结果,您需要等待值:

import scala.concurrent.duration._

Await.result(future, 1 second) //blocking

或使用回调:

import scala.util.{Failure, Success}

future.onComplete { //not blocking
    case Success(value) => println(value)
    case Failure(e) => e.printStackTrace
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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