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?

Willi Mentzel
  • 24,988
  • 16
  • 102
  • 110
djm.im
  • 3,153
  • 4
  • 26
  • 42

2 Answers2

8

Use minBy

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

s will be 1.

Willi Mentzel
  • 24,988
  • 16
  • 102
  • 110
4

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()
pwolaq
  • 6,123
  • 18
  • 45