Finding an item that matches predicate in Scala

前端 未结 4 1340
失恋的感觉
失恋的感觉 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条回答
  •  Happy的楠姐
    2021-02-01 01:37

    The scala way would be to use exists:

    collection.exists(item => condition1(item) && condition2(item))
    

    And since java 8 you can use anyMatch:

    collection.stream().anyMatch(item -> condition1(item) && condition2(item));
    

    which is much better than a plain for or foreach.

提交回复
热议问题