如果在Scala Map maxBy中没有明确的赢家,则无

时间:2018-02-06 01:32:51

标签: scala hashmap maxby

val valueCountsMap: mutable.Map[String, Int] = mutable.Map[String, Int]()
valueCountsMap("a") = 1
valueCountsMap("b") = 1
valueCountsMap("c") = 1

val maxOccurredValueNCount: (String, Int) = valueCountsMap.maxBy(_._2)
// maxOccurredValueNCount: (String, Int) = (b,1)

如果在执行maxBy值时没有明显的赢家,我怎么能得到None?我想知道scala可变映射中是否已经实现了任何本机解决方案。

1 个答案:

答案 0 :(得分:3)

不,对于你所描述的内容,没有原生的解决方案。

以下是我可以采取的措施。

implicit class UniqMax[K,V:Ordering](m: Map[K,V]) {
  def uniqMaxByValue: Option[(K,V)] = {
    m.headOption.fold(None:Option[(K,V)]){ hd =>
      val ev = implicitly[Ordering[V]]
      val (count, max) = m.tail.foldLeft((1,hd)) {case ((c, x), v) =>
        if (ev.gt(v._2, x._2)) (1, v)
        else if (v._2 == x._2) (c+1, x)
        else                   (c, x)
      }
      if (count == 1) Some(max) else None
    }
  }
}

用法:

Map("a"->11, "b"->12, "c"->11).uniqMaxByValue    //res0: Option[(String, Int)] = Some((b,12))
Map(2->"abc", 1->"abx", 0->"ab").uniqMaxByValue  //res1: Option[(Int, String)] = Some((1,abx))
Map.empty[Long,Boolean].uniqMaxByValue           //res2: Option[(Long, Boolean)] = None
Map('c'->2.2, 'w'->2.2, 'x'->2.1).uniqMaxByValue //res3: Option[(Char, Double)] = None