Scala 转换集到地图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4851418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:46:23  来源:igfitidea点击:

Scala Convert Set to Map

scalascala-collections

提问by Torsten Schmidt

How do I convert a Set("a","b","c") to a Map("a"->1,"b"->2,"c"->3)? I think it should work with toMap.

如何将 Set("a","b","c") 转换为 Map("a"->1,"b"->2,"c"->3)?我认为它应该与 toMap 一起使用。

回答by Adam Rabung

zipWithIndexis probably what you are looking for. It will take your collection of letters and make a new collection of Tuples, matching value with position in the collection. You have an extra requirement though - it looks like your positions start with 1, rather than 0, so you'll need to transform those Tuples:

zipWithIndex可能是您正在寻找的。它将获取您的字母集合并创建一个新的元组集合,将值与集合中的位置相匹配。不过你有一个额外的要求——看起来你的位置从 1 开始,而不是 0,所以你需要转换这些元组:

Set("a","b","c")
  .zipWithIndex    //(a,0), (b,1), (c,2)
  .map{case(v,i) => (v, i+1)}  //increment each of those indexes
  .toMap //toMap does work for a collection of Tuples

One extra consideration - Sets don't preserve position. Consider using a structure like List if you want the above position to consistently work.

一个额外的考虑 - 集合不保留位置。如果您希望上述职位始终有效,请考虑使用类似 List 的结构。

回答by Frank S. Thomas

Here is another solution that uses a Streamof all natural numbers beginning from 1 to be zipped with your Set:

这是另一种解决方案,它使用Stream从 1 开始的所有自然数的a与您的Set.

scala> Set("a", "b", "c") zip Stream.from(1) toMap
Map((a,1), (b,2), (c,3))

回答by GClaramunt

toMaponly works if the Setentries are key/value pairs (e.g. Set(("a",1),("b",2),("c",3))).

toMap仅当Set条目是键/值对时才有效(例如Set(("a",1),("b",2),("c",3)))。

To get what you want, use zipWithIndex:

要获得您想要的东西,请使用zipWithIndex

Set("a","b","c") zipWithIndex
// Set[(String, Int)] = Set((a,0), (b,1), (c,2))

or (as in you original question):

或(如你原来的问题):

Set("a","b","c") zip (1 to 3) toMap

回答by Viktor Nordling

This would also work:

这也可以:

(('a' to 'c') zip (1 to 3)).toMap