Reputation: 37
Currently, I am trying to write a method to locate the highest value product in my hashmap.
I am looking for a push in the right direction if that is possible. I appreciate any help that might be pointed my way. Thank you.
Upvotes: 1
Views: 585
Reputation: 1171
In order to be consistent, I would suggest you using horizontal tab \t
as the divider.
To align the text in the right columns, I would also create a method which adds some whitespaces right after the product name (e.g jeans). The number of input whitespaces should be equal to the subtraction of the column title (e.g Description) and the product name (e.g jeans).
Try this code:
fun addWhitespaces(input: String, referencedWord: String = "Description"): String
{
var ws = ""
(0..(referencedWord.length - input.length)).map { ws += " " }
return ws
}
The method addWhitespaces()
is called within the last print.
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}")
}
Also as Ali Gelenler mentioned, you should check for the null condition as the result of maxBy()
may be null.
Upvotes: 1
Reputation: 241
maxBy returns nullable Map.Entry so you need to handle nullable result. You could for example use safe call with ? following by let as below.
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}")
}
Upvotes: 0
Reputation: 80
Your print statement is the default format from the map entry. Change your print statement to something like this:
println("${highestPricedProduct.key}\t${highestPricedProduct.value.first}\t${highestPricedProduct.value.second}")
Upvotes: 0