0

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?

3
  • 2
    "aaaaaaaa" < "b" && "bbbbbbbbbbb" < "c" & "ccccccc" < "d", StringOrdering source code Commented Feb 3, 2019 at 13:37
  • Can you explain why you think "on" is lexicographically smaller than "bus"? At least in my language's alphabet "b" comes before "o", not after. In a lexicon in your native language, would the word "bus" come after the word "on"? Commented Feb 3, 2019 at 17:58
  • @JoergWMittag Thank you that's my doubt and so the reason of posting my question here. please read my question, I was confused it as the number of elements. Yes, in english language 'b' comes before 'o' and after 'a'. Thanks for enlightening me Commented Feb 3, 2019 at 22:42

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.