Scala: How to create a Map[K,V] from a Set[K] and a function from K to V?

前端 未结 7 1207
栀梦
栀梦 2020-12-15 07:37

What is the best way to create a Map[K,V] from a Set[K] and function from K to V?

For example, suppose I have

7条回答
  •  执念已碎
    2020-12-15 08:06

    In addition to the existing answers,

    Map() ++ set.view.map(i => i -> f(i))
    

    is pretty short and performs as well as the faster answers (fold/breakOut).

    (Note the view to prevent creation of a new collection; it does the remapping as it goes.)

提交回复
热议问题