首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在scala中组合fastutil贴图?

如何在scala中组合fastutil贴图?
EN

Stack Overflow用户
提问于 2019-02-06 03:08:04
回答 2查看 342关注 0票数 1

在scala中组合两个Object2IntOpenHashMapString最快的方法是什么?希望将这两个地图结合起来:

代码语言:javascript
复制
  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}的输出。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-02-06 04:52:08

下面是组合两个Object2IntOpenHashMap值的必备方法。

代码语言:javascript
复制
    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。我是用猫做的-

代码语言:javascript
复制
            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的文档。

票数 2
EN

Stack Overflow用户

发布于 2019-02-06 07:49:14

找到了使用快速输入集的替代方案:

代码语言:javascript
复制
  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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54541425

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档