映射 Scala Map 的键和值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9130368/
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
Map both keys and values of a Scala Map
提问by Alexey Romanov
Scala's MapLiketrait has a method
Scala 的MapLiketrait 有一个方法
mapValues [C] (f: (B) ? C): Map[A, C]
But I sometimes want a different type:
但有时我想要一种不同的类型:
mapKeysAndValues [C] (f: (A, B) ? C): Map[A, C]
Is there a simple way to do this which I am missing? Of course, this can be done with a fold.
有没有一种简单的方法可以做到这一点,而我却缺少这种方法?当然,这可以通过折叠来完成。
回答by tenshi
mapmethod iterates though all (key, value)pairs. You can use it like this:
map方法遍历所有(key, value)对。你可以这样使用它:
val m = Map("a" -> 1, "b" -> 2)
val incM = m map {case (key, value) => (key, value + 1)}
回答by Tomasz Nurkiewicz
What about this code:
这段代码怎么样:
val m = Map(1 -> "one", 2 -> "two")
def f(k: Int, v: String) = k + "-" + v
m map {case (k, v) => (k, f(k, v))}
Which produces:
产生:
Map(1 -> 1-one, 2 -> 2-two)
This can be packaged into utility method:
这可以打包成实用程序方法:
def mapKeysAndValues[A,B,C](input: Map[A,B], fun: (A, B) => C) =
input map {case(k,v) => (k, fun(k, v))}
Usage:
用法:
mapKeysAndValues(
Map(1 -> "one", 2 -> "two"),
(k: Int, v: String) => k + "-" + v
)
回答by Grigory Kislin
m map (t => (t._1, t._2 + 1))
m map (t => t._1 -> t._2 + 1)
回答by missingfaktor
With some Scalaz:
使用一些 Scalaz:
scala> def fst[A, B] = (x: (A, B)) => x._1
fst: [A, B]=> (A, B) => A
scala> Map(1 -> "Lorem", 2 -> "Ipsum").map(fst &&& Function.tupled(_.toString + _))
res1: scala.collection.immutable.Map[Int,java.lang.String] = Map(1 -> 1Lorem, 2 -> 2Ipsum)
I like @tenshi's solution better.
我更喜欢@tenshi 的解决方案。
回答by Alex
You could create a utility class:
您可以创建一个实用程序类:
class MyMapLike[K,V](m:MapLike[K,V,_]){
def mapKeysAndValues[R](f: (K, V) => R)={
m.map{case (k,v)=> f(k,v)}
}
}
object MyMapLike{
implicit def maplike2mymaplike[K,V](ml:MapLike[K,V,_]):MyMapLike[K,V]=new MyMapLike(m)
}
import MyMapLike._
Map(1 -> "one", 2 -> "two").mapKeysAndValues(k,v=>v*k)
Code not tested but it should work somehow simmilar like that.
代码未经测试,但它应该以某种方式类似那样工作。

