Xóa bài viết
Bạn có chắc chắn muốn xóa bài viết này không ?
Xóa bình luận
Bạn có chắc chắn muốn xóa bình luận này không ?
Kotlin Map collection with flatMap(), flatMapTo() methods
Kotlin Map collection with flatMap(), flatMapTo() methods
https://grokonez.com/kotlin/kotlin-map-collection-flatmap-flatmapto-methods
In the tutorial, JavaSampleApproach will show you how to work with Kotlin Map flatMap()
and flatMapTo()
methods.
I. Kotlin Map collection with flatMap(), flatMapTo()
1. with flatMap() method
We use flatMap()
to create a single list of all entries from results of [transform] function being invoked on each entry of original map.
Method signature:
public inline fun Map.flatMap(transform: (Map.Entry) -> Iterable): List
Practice:
val customerMap = mapOf(Pair(Customer("Jack", 25), Address("NANTERRE CT", "77471")),
Pair(Customer("Mary", 37), Address("W NORMA ST", "77009")),
Pair(Customer("Peter", 18), Address("S NUGENT AVE", "77571")),
Pair(Customer("Amos", 23), Address("E NAVAHO TRL", "77449")),
Pair(Customer("Craig", 45), Address("AVE N", "77587")))
val customerList = customerMap.flatMap { (customer, _) -> listOf(customer) }
customerList.forEach{ println(it) }
/*
Customer(name=Jack, age=25)
Customer(name=Mary, age=37)
Customer(name=Peter, age=18)
Customer(name=Amos, age=23)
Customer(name=Craig, age=45)
*/
val addressList = customerMap.flatMap { (_, address) -> listOf(address) }
addressList.forEach{ println(it) }
/*
Address(street=NANTERRE CT, postcode=77471)
Address(street=W NORMA ST, postcode=77009)
Address(street=S NUGENT AVE, postcode=77571)
Address(street=E NAVAHO TRL, postcode=77449)
Address(street=AVE N, postcode=77587)
*/
val customerInfos = customerMap.flatMap { (customer, address) -> listOf("${customer.name} lives at ${address.street}") }
customerInfos.forEach{ println(it) }
/*
Jack lives at NANTERRE CT
Mary lives at W NORMA ST
Peter lives at S NUGENT AVE
Amos lives at E NAVAHO TRL
Craig lives at AVE N
*/
More at:
Kotlin Map collection with flatMap(), flatMapTo() methods
https://grokonez.com/kotlin/kotlin-map-collection-flatmap-flatmapto-methods
Bình luận

{{ comment.user.name }}
Bỏ hay
Hay

Cùng một tác giả

1
0
Tutorial Link: (Link) (Ảnh) Django is a Pythonbased free and opensource web framework that follows the modeltemplateview architectural pattern. A...

1
0
https://loizenai.com/angular11nodejspostgresqlcrudexample/ Angular 11 Node.js PostgreSQL Crud Example (Ảnh) Tutorial: “Angular 11 Node.js Postg...

1
0
Angular Spring Boot jwt Authentication Example Github https://loizenai.com/angularspringbootjwt/ (Ảnh) Tutorial: ” Angular Spring Boot jwt Authe...
Bài viết liên quan

0
0
https://grokonez.com/kotlin/kotlinreadwritecsvfileexample How to read/write CSV file in Kotlin In this tutorial, we're gonna look at examples tha...