Kotlin 从HashMap打印值
目前,我正在尝试编写一个方法来定位hashmap中的最高值产品Kotlin 从HashMap打印值,kotlin,Kotlin,目前,我正在尝试编写一个方法来定位hashmap中的最高值产品 如果可能的话,我正在寻找一个正确的方向。我感谢任何可能为我指明方向的帮助。谢谢。您的打印语句是地图条目中的默认格式。将打印语句更改为以下内容: println("${highestPricedProduct.key}\t${highestPricedProduct.value.first}\t${highestPricedProduct.value.second}") maxBy返回可为空的Map.Entry,所以您需要处理可为空
如果可能的话,我正在寻找一个正确的方向。我感谢任何可能为我指明方向的帮助。谢谢。您的打印语句是地图条目中的默认格式。将打印语句更改为以下内容:
println("${highestPricedProduct.key}\t${highestPricedProduct.value.first}\t${highestPricedProduct.value.second}")
maxBy返回可为空的Map.Entry,所以您需要处理可为空的结果。例如,您可以使用安全呼叫?下面是let,如下所示
products.maxBy { it.value.second }?.let {
val (key, value) = it
println("The highest priced product is: ")
println()
println("Item# Description Price")
println("----- ------------- -------")
println("$key ${value.first} ${value.second}")
}
为了保持一致,我建议您使用水平选项卡
\t
作为分隔符
为了对齐右列中的文本,我还将创建一个方法,在产品名称后面添加一些空格(例如jeans)。输入空白的数量应等于列标题(如描述)和产品名称(如牛仔裤)的减法
请尝试以下代码:
fun addWhitespaces(input: String, referencedWord: String = "Description"): String
{
var ws = ""
(0..(referencedWord.length - input.length)).map { ws += " " }
return ws
}
方法addWhitespaces()
在上次打印中被调用
products.maxBy { it.value.second } ?.let { (key, value) ->
println("The highest priced product is: ")
println()
println("Item#\tDescription\tPrice")
println("-----\t-----------\t-----")
println("$key \t${value.first}${addWhitespaces(value.first)}\t${value.second}")
}
同样如前所述,您应该检查null条件,因为
maxBy()
的结果可能为null。highestPricedProduct
是一个映射。条目
,您必须使用字符串使用正确的格式化方式进行打印。格式
添加空格(a,b)
可以简化为@pixix4 Oh cool,我不知道这个方法存在。感谢您改进我的解决方案。