1. Overview
In this tutorial, we’ll see how to find the min and max of different collections in Scala.
2. Find the Min and Max of a Collection
Scala provides several generic methods for all collections. Fortunately for us, it offers easy-to-use methods to find the min and max of collections.
In this section, we’ll see examples using List, Set, Array, Vector, and Seq.
2.1. List
Let’s use List as our first example to find the min and max:
scala> val lst = List(3,4,1,2)
lst: List[Int] = List(3, 4, 1, 2)
scala> lst.min
res0: Int = 1
scala> lst.max
res1: Int = 4
As we can see, it’s very simple to get the min and max elements of a List.
But what happens if the List is empty? Let’s take a look:
scala> val empty = List.empty[Int]
empty: List[Int] = List()
scala> empty.max
java.lang.UnsupportedOperationException: empty.max
at scala.collection.TraversableOnce.max(TraversableOnce.scala:275)
at scala.collection.TraversableOnce.max$(TraversableOnce.scala:273)
at scala.collection.AbstractTraversable.max(Traversable.scala:108)
... 26 elided
We get an exception if we try to find the max or min of an empty List. The same thing will also happen for every other collection mentioned in this article.
2.2. Set
Here’s how we find the min and max of a Set:
scala> val s = Set(1,2,3,4)
s: scala.collection.immutable.Set[Int] = Set(1, 2, 3, 4)
scala> s.max
res0: Int = 4
scala> s.min
res1: Int = 1
2.3. Array
Let’s see how we can find the min and max of an Array:
scala> val arr = Array(1,4,3,2)
arr: Array[Int] = Array(1, 4, 3, 2)
scala> arr.max
res2: Int = 4
scala> arr.min
res3: Int = 1
2.4. Vector
Now, let’s find the min and max of a Vector:
scala> val vec = Vector(1,4,3,2)
vec: scala.collection.immutable.Vector[Int] = Vector(1, 4, 3, 2)
scala> vec.max
res4: Int = 4
scala> vec.min
res5: Int = 1
2.5. Seq
Finally, let’s find the min and max of an Seq:
scala> val seq = Seq(1,4,3,2)
seq: Seq[Int] = List(1, 4, 3, 2)
scala> seq.max
res6: Int = 4
scala> seq.min
res7: Int = 1
As we can see, the usage is the same, and the result is the expected one.
3. Conclusion
In this article, we saw how to find the min and max of different collections in Scala.