string Scala检查元素是否存在于列表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14267612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:46:54  来源:igfitidea点击:

Scala check if element is present in a list

stringlistscalafind

提问by Dario Oddenino

I need to check if a string is present in a list, and call a function which accepts a boolean accordingly.

我需要检查列表中是否存在字符串,并相应地调用一个接受布尔值的函数。

Is it possible to achieve this with a one liner?

有没有可能用一个衬垫来实现这一点?

The code below is the best I could get:

下面的代码是我能得到的最好的:

val strings = List("a", "b", "c")
val myString = "a"

strings.find(x=>x == myString) match {
  case Some(_) => myFunction(true)
  case None => myFunction(false)
}

I'm sure it's possible to do this with less coding, but I don't know how!

我确信可以用更少的编码来做到这一点,但我不知道怎么做!

回答by Kim Stebel

Just use contains

只需使用 contains

myFunction(strings.contains(myString))

回答by Matt Hughes

And if you didn't want to use strict equality, you could use exists:

如果你不想使用严格相等,你可以使用exists:


myFunction(strings.exists { x => customPredicate(x) })

回答by Taylrl

Even easier!

更轻松!

strings contains myString

回答by DanieleDM

this should work also with different predicate

这也应该适用于不同的谓词

myFunction(strings.find( _ == mystring ).isDefined)

回答by guykaplan

In your case I would consider using Set and not List, to ensure you have unique values only. unless you need sometimes to include duplicates.

在您的情况下,我会考虑使用 Set 而不是 List,以确保您只有唯一的值。除非您有时需要包含重复项。

In this case, you don't need to add any wrapper functions around lists.

在这种情况下,您不需要在列表周围添加任何包装函数。

回答by Johnny

You can also implement a containsmethod with foldLeft, it's pretty awesome. I just love foldLeft algorithms.

您还可以使用 实现一个contains方法foldLeft,它非常棒。我只是喜欢 foldLeft 算法。

For example:

例如:

object ContainsWithFoldLeft extends App {

  val list = (0 to 10).toList
  println(contains(list, 10)) //true
  println(contains(list, 11)) //false

  def contains[A](list: List[A], item: A): Boolean = {
    list.foldLeft(false)((r, c) => c.equals(item) || r)
  }
}