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

前端 未结 7 1209
栀梦
栀梦 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:02

    What about this:

    (s map { i => i -> func(i) }).toMap
    

    This maps the elements of s to tuples (i, func(i)) and then converts the resulting collection to a Map.

    Note: i -> func(i) is the same as (i, func(i)).

    dbyrne suggests creating a view of the set first (see his answer and comments), which prevents an intermediate collection from being made, improving performance:

    (s.view map { i => i -> func(i) }).toMap
    

提交回复
热议问题