在scala中组合两个Object2IntOpenHashMapString最快的方法是什么?希望将这两个地图结合起来:
val foo = new Object2IntOpenHashMap[String]
foo.put("foo", 1)
val bar = new Object2IntOpenHashMap[String]
bar.put("foo", 1)
bar.put("bar", 1)并产生{"foo“:2,"bar”:1}的输出。
发布于 2019-02-06 04:52:08
下面是组合两个Object2IntOpenHashMap值的必备方法。
val foo = new Object2IntOpenHashMap[String]
foo.put("foo", 1)
val bar = new Object2IntOpenHashMap[String]
bar.put("foo", 1)
bar.put("bar", 1)
bar.keySet().forEach(x => {
val barValue = bar.getInt(x)
foo.computeInt(x , (_, v) => if(v == null) barValue else barValue + v)
})
println(foo)上面的println(foo)将打印{bar=>1, foo=>2}。
但是如果你想要更多的功能,你应该使用更多的功能库,比如cat或者scalaz。我是用猫做的-
import cats.Semigroup
import cats.implicits._
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap
implicit val Object2IntOpenHashMapSemiGroup = new Semigroup[Object2IntOpenHashMap[String]] {
override def combine(x: Object2IntOpenHashMap[String], y: Object2IntOpenHashMap[String]): Object2IntOpenHashMap[String] = {
val result: Object2IntOpenHashMap[String] = y.clone()
x.keySet().forEach(x => {
val barValue = y.getInt(x)
result.computeInt(x , (_, v) => if(v == null) barValue else barValue +v)
})
result
}
}
println(foo combine bar)
println(Object2IntOpenHashMapSemiGroup.combine(foo, bar))您将获得与之前相同的结果。您可以在此处查看semigroup here的文档。
发布于 2019-02-06 07:49:14
找到了使用快速输入集的替代方案:
val foo = new Object2IntOpenHashMap[String]
foo.put("foo", 1)
val bar = new Object2IntOpenHashMap[String]
bar.put("foo", 1)
bar.put("bar", 1)
val mapIter = bar.object2IntEntrySet().fastIterator()
while(mapIter.hasNext()) {
val x = mapIter.next()
foo.put(x.getKey(), x.getIntValue() + foo.getOrDefault(x.getKey(), 0))
}
println(foo)https://stackoverflow.com/questions/54541425
复制相似问题