如何在Scala中组合fastutil映射?

时间:2019-02-05 19:08:04

标签: scala fastutil

在scala中组合两个Object2IntOpenHashMap [String]的最快方法是什么?希望合并这两个地图:

use Illuminate\Database\Eloquent\Collection; // As per Mihir Bhende's answer, make sure we're using the correct Eloquent `Collection`

$collection = new Collection;

并产生{“ foo”:2,“ bar”:1}的输出。

2 个答案:

答案 0 :(得分:2)

下面是组合两个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))

您将获得与以前相同的结果。您可以在这里查看here半小组的文档。

答案 1 :(得分:0)

使用快速输入集找到了另一种方法:

  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)