user2708013
user2708013

Reputation: 417

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?

Upvotes: 0

Views: 2556

Answers (2)

senjin.hajrulahovic
senjin.hajrulahovic

Reputation: 3191

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

Upvotes: 4

Alexey Novakov
Alexey Novakov

Reputation: 764

min function uses Java String compareTo method to compare a Unicode value of each character in the strings.

If we compare on and bus, then bus will be smaller:

@ "on".compareTo("bus")
res16: Int = 13

13 is difference of integer values of o and b. Also, return value is positive, which means left operant is greater than right operand.

and on is smaller than wheels and so on:

@ "on".compareTo("wheels")
res17: Int = -8

Here we have negative return value, which means left operand is smaller tha right operand.

See more information here: https://www.journaldev.com/18009/java-string-compare

Upvotes: 3

Related Questions