在 scala 列表中搜索与属性匹配的内容

发布于 2024-10-16 01:49:12 字数 284 浏览 3 评论 0原文

执行此操作的惯用 scala 方法是什么?我有一个列表,如果我找到符合某些条件的内容,则希望返回“Y”,否则返回“N”。我有一个“有效”的解决方案,但我不喜欢它......

def someMethod( someList: List[Something]) : String = {

someList.foreach( a =>
  if (a.blah.equals("W") || a.bar.equals("Y") ) {
    return "Y"
  }
 )
  "N"


}

What is the idiomatic scala way to do this? I have a list, and want to return a "Y" if I find something that matches some conditions, else a "N". I have a solution that "works", but I don't like it...

def someMethod( someList: List[Something]) : String = {

someList.foreach( a =>
  if (a.blah.equals("W") || a.bar.equals("Y") ) {
    return "Y"
  }
 )
  "N"


}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

独夜无伴 2024-10-23 01:49:12

简单:

if (someList.exists{ a=> a.blah == "W" || a.bar == "Y"}) 
   "Y"
else 
   "N"

Simples:

if (someList.exists{ a=> a.blah == "W" || a.bar == "Y"}) 
   "Y"
else 
   "N"
后知后觉 2024-10-23 01:49:12
def condition(i: Something) = i.blah.equals("W") || i.bar.equals("Y")

somelist.find(condition(_)).map(ignore => "Y").getOrElse("N")

或者简单地

if (somelist exists condition) "Y" else "N"
def condition(i: Something) = i.blah.equals("W") || i.bar.equals("Y")

somelist.find(condition(_)).map(ignore => "Y").getOrElse("N")

or simply

if (somelist exists condition) "Y" else "N"
蓝颜夕 2024-10-23 01:49:12

假设 Something 有一个 blah 成员。

def someMethod(someList: List[Something]): String = 
  if (someList forall { a => a.blah == "W" || a.blah == "Y" }) "Y" else "N"

Assuming that Something has a blah member.

def someMethod(someList: List[Something]): String = 
  if (someList forall { a => a.blah == "W" || a.blah == "Y" }) "Y" else "N"
放我走吧 2024-10-23 01:49:12
val l = List(1,2,3,4)

(l.find(x => x == 0 || x == 1)) match { case Some(x) => "Y"; case _ => "N"}
res: java.lang.String = Y
val l = List(1,2,3,4)

(l.find(x => x == 0 || x == 1)) match { case Some(x) => "Y"; case _ => "N"}
res: java.lang.String = Y
人心善变 2024-10-23 01:49:12

假设 Something 可以模式匹配,例如,当它是一个像...这样的案例类时

case class Something(blah:String, bar:String) 

,您可以写...

 def someMethod(someList: List[Something]) = someList.collect{
   case Something("W",_) | Something(_,"Y") => "Y"}.headOption.getOrElse("N")

Assuming Something can pattern match, e.g. when it is a case class like...

case class Something(blah:String, bar:String) 

... you can write...

 def someMethod(someList: List[Something]) = someList.collect{
   case Something("W",_) | Something(_,"Y") => "Y"}.headOption.getOrElse("N")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文