I have such a code, in general it works correctly, but if there is a maximum long word and it is followed by the same words in length, then it will return only 1 long word, and I need to get the last long word. Here's what I mean, such input: AWord BWord ALongWord BLongWord CLongWord. My code will output an (A)ALongWord but should output a (C)CLongWord because it is the most recent.
fun main(){
val result1 = readLine()?.split(" ")?.associateWith { it.length }?.maxBy { it.value }.let{it?.key?.get(0)}.let { println(it) }
}
I assume that this can be done with reduce, but I don't quite understand how, probably my implementation needs to be redone because maxBy does not allow it to be done, if possible, fix my code or offer your solution. This is a learning task and it involves using functions over collections.
maxBy
finds the first occurrence of the maximum element, not the last.If you want the last maximum element, you can simply do
maxBy
after reversing (asReversed
) the list of strings you got fromsplit
.Consider using
maxByOrNull
instead ofmaxBy
so that you get anull
instead of an exception when the user entered nothing.Also, I'm not sure why you made a map out of this. That is unnecessary. You also shouldn't assign the result of
let { println(...) }
to aval
. That is theUnit
object, not the result you want.If you want to store the result somewhere and also print it, use
also
: