0

I have a String array and I need to find what is the length of the shortest string. For example, for this string array ["abc", "ab", "a"] I should get value 1.

I wrote method that gets a string array and returns int value

val minLength = fun(strs: Array<String>): Int {
    var minLength = strs[0].length
    for (index in 1..strs.size - 1) {
        val elemLen = strs[index].length
        if (minLength > elemLen) {
            minLength = elemLen
        }
    }
    return minLength
}

Another approach is to use reduce method

val minLengthReduce = strs.reduce ({
    str1, str2 ->
    if (str1.length < str2.length) str1 else str2
}).length

Is it possible to get int value directly from reduce() method instead string value?

I found this question about reduce and fold methods.

Should I use fold method instead reduce?

2 Answers 2

8

Use minBy

val a = arrayOf("a", "abc", "b")
val s = a.minBy(String::length)?.length ?: 0

s will be 1.

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

Comments

5

Another approach is to map strings to their length and then choose the smallest number:

val strs = arrayOf("abc", "ab", "ab")
val min = strs.map(String::length).min()

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.