Skip to content

Instantly share code, notes, and snippets.

@jonjack
Last active November 7, 2018 23:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonjack/b825fb12fb5c4adb9e67ababe510215f to your computer and use it in GitHub Desktop.
Save jonjack/b825fb12fb5c4adb9e67ababe510215f to your computer and use it in GitHub Desktop.
Random Scala snippets

Return the max value of a List[Int] if unique, otherwise return -1.

def maxIfUnique(li: List[Int]) = li.groupBy(_.intValue).maxBy(_._1)._2 match {
  case x if x.size == 1 => x.head
  case _ => -1
}

scala> val list = List(1, 2, 1)   // 2 is max and is unique
scala> maxIfUnique(list)
res61: Int = 2

scala> val list = List(3, 3, 1)   // 3 is max but not unique
scala> maxIfUnique(list)
res62: Int = -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment