Search code examples
arraysscalamaxminarraybuffer

Finding min and max of a given array in scala


I have an array as below. what I am trying to understand are min and max inbuilt functions.

val bf=Array("wheels","on","the","bus")

For Max, the output is "wheels" which is right because the number of elements for wheels is big compared to others But when I try bf.min. I get the output as "bus". If min gives element with minimum elements then it should be "on"? am I right? what am I missing here? can someone please help me understand what am I doing wrong?


Solution

  • Alphanumeric order is used by default, when comparing strings.

    You want to use minBy, maxBy if you want to get the shortest or longest string respectively.

    bf.minBy(_.length)
    

    Array#maxBy