简体   繁体   中英

Scala: How to find the minimum of more than 2 elements?

Since the Math.min() function only allows for the use of 2 elements, I was wondering if there is maybe another function which can calculate the minimum of more than 2 elements.

Thanks in advance!

If you have multiple elements you can just chain calls to the min method:

Math.min(x, Math.min(y, z))

Since scala adds the a min method to numbers via implicits you could write the following which looks much fancier:

x min y min z

If you have a list of values and want to find their minimum:

val someNumbers: List[Int] = ???
val minimum = someNumbers.min

Note that this throws an exception if the list is empty. From scala 2.13.x onwards, there will be a minOption method to handle such cases gracefully. For older versions you could use the reduceOption method as workaround:

someNumbers.reduceOption(_ min _)
someNumbers.reduceOption(Math.min)

Add all numbers in the collection like the list and find a minimum of it.

scala> val list = List(2,3,7,1,9,4,5)
list: List[Int] = List(2, 3, 7, 1, 9, 4, 5)

scala> list.min
res0: Int = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM