1
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 mutable Maps 中是否已经实现了任何本机解决方案。

4

1 回答 1

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
于 2018-02-06T03:42:45.737 回答