Kotlin collection methods – groupBy(), sumByDouble(), mapValues(), toSortedMap() example
https://grokonez.com/kotlin/kotlin-collection-methods-groupby-sumbydouble-mapvalues-tosortedmap
In the tutorial, Grokonez will show you how to combine Kotlin collection methods: groupBy()
, sumByDouble()
with Kotlin List and mapValues()
, toSortedMap()
with Kotlin Map.
1. Kotlin collection methods - groupBy(), sumByDouble(), mapValues(), toSortedMap()
groupBy()
with method signature:
public inline fun Iterable.groupBy(keySelector: (T) -> K): Map>
-> groupBy()
is used to group elements of the given collection by the key returned by the given [keySelector] function. Result is a map collection.
Practice:
val productList = listOf(Product("iPhone 8 Plus 64G", "Apple", 850.00),
Product("Samsung Galaxy S8 64GB Unlocked Phone", "Samsung", 699.99),
Product("iPad Pro 9.7-inch 32 GB", "Apple", 474.98),
Product("Samsung Electronics Ultra HD Smart LED TV", "Samsung", 677.92),
Product("Google Pixel Phone - 5 inch display", "Google", 279.95),
Product("iPad Pro 9.7-inch 128G", "Apple", 574.99),
Product("Google Wifi system 1-Pack", "Google", 149.90),
Product("Samsung Galaxy Tab 4", "Samsung", 127.67))
val groupProductsWithMadeBy = productList.groupBy { it-> it.madeBy }
groupProductsWithMadeBy.forEach { println(it) }
/*
Apple=[Product(name=iPhone 8 Plus 64G, madeBy=Apple, price=850.0), Product(name=iPad Pro 9.7-inch 32 GB, madeBy=Apple, price=474.98), Product(name=iPad Pro 9.7-inch 128G, madeBy=Apple, price=574.99)]
Samsung=[Product(name=Samsung Galaxy S8 64GB Unlocked Phone, madeBy=Samsung, price=699.99), Product(name=Samsung Electronics Ultra HD Smart LED TV, madeBy=Samsung, price=677.92), Product(name=Samsung Galaxy Tab 4, madeBy=Samsung, price=127.67)]
Google=[Product(name=Google Pixel Phone - 5 inch display, madeBy=Google, price=279.95), Product(name=Google Wifi system 1-Pack, madeBy=Google, price=149.9)]
*/
More at:
Kotlin collection methods – groupBy(), sumByDouble(), mapValues(), toSortedMap() example
https://grokonez.com/kotlin/kotlin-collection-methods-groupby-sumbydouble-mapvalues-tosortedmap
Top comments (0)