DEV Community

loizenai
loizenai

Posted on

Kotlin Map methods – maxBy() maxWith()

https://grokonez.com/kotlin/kotlin-map-methods-maxby-maxwith

Kotlin Map methods – maxBy() maxWith()

In the tutorial, JavaSampleApproach will show how to use Kotlin Map methods maxBy(), maxWith().

I. Kotlin Map methods - maxBy() maxWith()

1. maxBy()

maxBy() returns the first entry having largest value of the given function selector: (Map.Entry) -> R or 'null' if there are no elements.
Method signature:


public inline fun > Map.maxBy(selector: (Map.Entry) -> R): Map.Entry?

Practice:


val productMap = hashMapOf("iPhone 8 Plus 64G" to  Product("iPhone 8 Plus 64G", "Apple", 850.00),
                            "Samsung Galaxy S8 64GB Unlocked Phone" to Product("Samsung Galaxy S8 64GB Unlocked Phone", "Samsung", 699.99),
                            "iPad Pro 9.7-inch 32 GB" to Product("iPad Pro 9.7-inch 32 GB", "Apple", 474.98),
                            "Samsung Electronics Ultra HD Smart LED TV" to Product("Samsung Electronics Ultra HD Smart LED TV", "Samsung", 677.92),
                            "Google Pixel Phone - 5 inch display" to Product("Google Pixel Phone - 5 inch display", "Google", 279.95),
                            "iPad Pro 9.7-inch 128G" to Product("iPad Pro 9.7-inch 128G", "Apple", 574.99),
                            "Google Wifi system 1-Pack" to Product("Google Wifi system 1-Pack", "Google", 149.90),
                            "Samsung Galaxy Tab 4" to Product("Samsung Galaxy Tab 4", "Samsung", 127.67))

// public inline fun > Map.maxBy(selector: (Map.Entry) -> R): Map.Entry?
var productsWithMaxPrice = productMap.maxBy { (_, product) -> product.price }
println("Key: ${productsWithMaxPrice?.key}, Value: ${productsWithMaxPrice?.value}")
// print on console
// ->
/*
    Key: iPhone 8 Plus 64G, Value: Product(name=iPhone 8 Plus 64G, madeBy=Apple, price=850.0)
*/

2. maxWith()

maxWith() returns the first entry having the largest value according to the provided [comparator]
Method signature:

More at:

https://grokonez.com/kotlin/kotlin-map-methods-maxby-maxwith

Kotlin Map methods – maxBy() maxWith()

Top comments (0)