Finding an item that matches predicate in Scala

前端 未结 4 1378
失恋的感觉
失恋的感觉 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:19

    Testing if value matching predicate exists

    If you're just interested in testing if a value exists, you can do it with.... exists

    scala> val l=(1 to 4) toList
    l: List[Int] = List(1, 2, 3, 4)
    
    scala> l exists (_>5)
    res1: Boolean = false
    
    scala> l exists (_<2)
    res2: Boolean = true
    
    scala> l exists (a => a<2 || a>5)
    res3: Boolean = true
    

    Other methods (some based on comments):

    Counting matching elements

    Count elements that satisfy predicate (and check if count > 0)

    scala> (l count (_ < 3)) > 0
    res4: Boolean = true
    

    Returning first matching element

    Find the first element that satisfies predicate (as suggested by Tomer Gabel and Luigi Plinge this should be more efficient because it returns as soon as it finds one element that satisfies the predicate, rather than traversing the whole List anyway)

    scala> l find (_ < 3)
    res5: Option[Int] = Some(1) 
    
    // also see if we found some element by
    // checking if the returned Option has a value in it
    scala> l.find(_ < 3) isDefined
    res6: Boolean = true
    

    Testing if exact value exists

    For the simple case where we're actually only checking if one specific element is in the list

    scala> l contains 2
    res7: Boolean = true
    

提交回复
热议问题