Find a scala list for something matching the property

What is the idiomatic way of scala for this? I have a list, and I want to return "Y" if I find something that meets certain conditions, otherwise "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"


}
+3
source share
5 answers

Simples:

if (someList.exists{ a=> a.blah == "W" || a.bar == "Y"}) 
   "Y"
else 
   "N"
+11
source
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"
+8
source

, - .

def someMethod(someList: List[Something]): String = 
  if (someList forall { a => a.blah == "W" || a.blah == "Y" }) "Y" else "N"
+2
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
+1

, Something , . case, ...

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

... ...

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

Source: https://habr.com/ru/post/1790014/


All Articles