Scalaで述語に一致する項目を検索する 質問する

Scalaで述語に一致する項目を検索する 質問する

私は、Scala コレクションで、ある述語に一致するリスト内の項目を検索しようとしています。戻り値は必ずしも必要ではなく、リストにそれが含まれているかどうかをテストするだけです。

Java では、次のようなことを行います。

for ( Object item : collection ) {
    if ( condition1(item) && condition2(item) ) {
       return true;
    }
}
return false;

Groovy では、次のようなことができます。

return collection.find { condition1(it) && condition2(it) } != null

Scala でこれを行うための慣用的な方法は何ですか? もちろん、Java のループ スタイルを Scala に変換することもできますが、これを行うにはより機能的な方法があるように感じます。

ベストアンサー1

フィルターを使用する:

scala> val collection = List(1,2,3,4,5)
collection: List[Int] = List(1, 2, 3, 4, 5)

// take only that values that both are even and greater than 3 
scala> collection.filter(x => (x % 2 == 0) && (x > 3))
res1: List[Int] = List(4)

// you can return this in order to check that there such values
scala> res1.isEmpty
res2: Boolean = false

// now query for elements that definitely not in collection
scala> collection.filter(x => (x % 2 == 0) && (x > 5))
res3: List[Int] = List()

scala> res3.isEmpty
res4: Boolean = true

ただし、確認だけが必要な場合は、以下を使用しますexists

scala> collection.exists( x => x % 2 == 0 )
res6: Boolean = true

おすすめ記事