我试过使用.maxBy .max()和collection.Max,但我只能打印出每个元素都是最大的。
val fileName = "src/products.txt"
var products = HashMap<Int, Pair<String, Double>>()
var inputFD = File(fileName).forEachLine {
var pieces = it.split(",")
println("Item# Description Price")
println("----- ------------- ------")
for ( (pro,ducts) in products.toSortedMap() ) {
var pax = mutableListOf(ducts).maxBy { it -> it.second }
var highest = listOf<Double>(ducts.second).max()
println("The highest priced record is ${highest}")
}
文件是这样设置的(111, shoe, 9.99)
产出是这样的最高价记录是[(裤子,89.99)]最高价记录是[(鞋子,49.99)]。
你试图在for-loop中打印值,因此它是为每个产品打印的。而且变量在循环中每次都会被初始化,所以每个值都会是最大值。
这里是正确的方法。请注意,你可以在不使用可变变量的情况下解决它。
val fileName = "src/products.txt"
val products = File(fileName).readLines() //read all lines from file to a list
.map { it.split(",") } // map it to list of list of strings split by comma
.map { it[0] to it[1].toDouble() } // map each product to its double value in a Pair
.toMap() // convert list of Pairs to a Map
println("Item# Description Price")
println("----- ------------- ------")
products.keys.forEachIndexed { index, desc ->
println("$index\t$desc\t${products[desc]}")
}
println("The highest priced record is ${products.maxBy { it.value }}")