繁体   English   中英

比较两个列表的功能等效

[英]Functional equivalent of comparing two Lists

下面的代码比较两个列表,如果一个元素包含在另一个列表中,则输出该元素:

  var containList = new scala.collection.mutable.ListBuffer[String]()
                                                  //> containList  : scala.collection.mutable.ListBuffer[String] = ListBuffer()
  val lines2 = List("2", "3", "4")                //> lines2  : List[String] = List(2, 3, 4)
  for (l <- lines2) {
    isStringInFile(l)
  }

  def isStringInFile(str: String) = {
    val lines = List("115", "t2t", "3")
    for (l2 <- lines) {
      if (l2.contains(str)) {
        containList += l2
      }
    }
  }                                               //> isStringInFile: (str: String)Unit

  for (c <- containList) {
    println(c)                                    //> t2t
                                                  //| 3
  }

这是当务之急。 但是有功能实现吗?

有多种方法可以做到这一点

scala>   val lines2 = List("2", "3", "4")
lines2: List[String] = List(2, 3, 4)

scala> val lines = List("115", "t2t", "3")
lines: List[String] = List(115, t2t, 3)

scala> lines2.filter(lines.contains(_))
res1: List[String] = List(3)

另一种方法

scala> lines.intersect(lines2)
res2: List[String] = List(3)

我喜欢@mohit的解决方案,但您的预期结果与他的不同。 因此,此代码作为您的示例:

val lines2 = List("2", "3", "4")
val lines = List("115", "t2t", "3")

val result = for {l <- lines
     l2 <- lines2
     if l.contains(l2)
} yield l

result.foreach(println)

输出:

t2t
3

暂无
暂无

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

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