Finding an item that matches predicate in Scala

前端 未结 4 1290
失恋的感觉
失恋的感觉 2021-02-01 00:45

I\'m trying to search a scala collection for an item in a list that matches some predicate. I don\'t necessarily need the return value, just testing if the list contains it.

4条回答
  •  北海茫月
    2021-02-01 01:40

    Use filter:

    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
    

    But if all you need is to check use exists:

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

提交回复
热议问题