9

Anyone knows whats the Scala equivalent of the below java stream operation - findFirst()

lst.stream()
    .filter(x -> x > 5)
    .findFirst()

Thank you

Anand
  • 601
  • 2
  • 7
  • 17
  • `lst.filter(_ > 5).head` – jwvh Nov 04 '15 at 05:14
  • In java streams, the operation is interleaved. I.e. the filtering stops at the first element which is greater than 5. But in Scala normal list, it will first filter the enter list to create a sub list of all elements and take the head. I want the exact java streams effect. – Anand Nov 04 '15 at 05:38
  • If you want lazy filter, use `withFilter` or `list.view.filter` (later also works for `map` and several other common operations). If you need to find the first matched element, use `find`. – Aivean Nov 04 '15 at 05:49

2 Answers2

13

You can simple use lst.find(_ > 5) which will return an Option. This is basically the same as (but more efficient than) writing lst.filter(_ > 5).headOption which will also return an Option or swapping headOption for head (highly discouraged) which will throw an exception if nothing is found.

Seth Tisue
  • 29,985
  • 11
  • 82
  • 149
tryx
  • 975
  • 7
  • 17
  • This operation is an eger one right? It will first filter and create a sub list and then takes the head/headoption right? I want a lazy one which just stops filtering the moment it gets the first match ( > 5) – Anand Nov 04 '15 at 05:43
  • 2
    @Anand, If you need only one element, than use `find`. It will stop scanning list as soon as element is found. – Aivean Nov 04 '15 at 05:47
-1

As @Aivean noted:

scala> List(1,2,3,4,5,6,7,8,9,10).view.find(_ > 5)
res0: Option[Int] = Some(6)

See these questions:

In Scala, what does "view" do?

What is the difference between the methods iterator and view?

Community
  • 1
  • 1
Brian
  • 20,195
  • 6
  • 34
  • 55
  • 1
    `.view` should not be needed before `.find`, as `.find` will automatically stop after finding the first matching element. – ntn Nov 04 '15 at 07:05