How to find a matching element in a list and map it in as an Scala API method?

后端 未结 4 455
被撕碎了的回忆
被撕碎了的回忆 2021-02-05 06:42

Is there a method to do the following without doing both methods: find and map?

val l = 0 to 3
l.find(_ * 33 % 2 == 0).map(_ * 33) //          


        
4条回答
  •  心在旅途
    2021-02-05 07:44

    If you don't want to do your map() operation multiple times (for instance if it's an expensive DB lookup) you can do this:

    l.view.map(_ * 33).find(_ % 2 == 0)

    The view makes the collection lazy, so the number of map() operations is minimized.

提交回复
热议问题