本节主要介绍了Kotlin
标准库中提供的对于集合的扩展,都是非常实用强大的功能
我们通过为Shop
类编写各种功能的扩展来练习这部分功能,测试数据在对应测试目录下的TestShop.kt
13. n13Introduction
获取Shop
中Customer
的集合
fun Shop.getSetOfCustomers(): Set<Customer> {
return customers.toSet()
}复制代码
14. n14FilterMap
Kotlin
为集合扩展了filter
,map
,forEach
等等方法,这些在Java
中称为Steram Api
,功能都是相似的,但是无疑Kotlin
用起来更方便
本练习要求我们获取所有Customser
的City
,并放到一个Set
中,还有获取来自某一个City
的所有Customer
的List
fun Shop.getCitiesCustomersAreFrom(): Set<City> {
return customers.map { it.city }.toSet()
}复制代码
fun Shop.getCustomersFrom(city: City): List<Customer> {
// Return a list of the customers who live in the given city
return customers.filter { it.city==city }
}复制代码
15. n15AllAnyAndOtherPredicates
检查Customer
是否来自某一City
fun Customer.isFrom(city: City): Boolean {
// Return true if the customer is from the given city
return this.city == city
}复制代码
检查多个Customer
是否来自同一City
fun Shop.checkAllCustomersAreFrom(city: City): Boolean {
// Return true if all customers are from the given city
return customers.all { it.city == city }
}复制代码
检查是否有Customer
来自指定City
fun Shop.hasCustomerFrom(city: City): Boolean {
// Return true if there is at least one customer from the given city
return customers.any { it.city == city }
}复制代码
统计来自某一City
的Customer
的数量
fun Shop.countCustomersFrom(city: City): Int {
// Return the number of customers from the given city
return customers.count { it.city == city }
}复制代码
查找来自指定City
的第一个Customer
,没有找到的话返回null
fun Shop.findFirstCustomerFrom(city: City): Customer? {
// Return the first customer who lives in the given city, or null if there is none
return customers.firstOrNull { it.city == city }
}复制代码
16. n16FlatMap
获取Customer
订购的Product
集合
val Customer.orderedProducts: Set<Product> get() {
// Return all products this customer has ordered
return orders.flatMap { it.products }.toSet()
}复制代码
获取Shop
卖出的Product
集合
val Shop.allOrderedProducts: Set<Product> get() {
// Return all products that were ordered by at least one customer
return customers.flatMap { it.orderedProducts }.toSet()
}复制代码
17. n17MaxMin.kt
查找Order
最多的Customer
fun Shop.getCustomerWithMaximumNumberOfOrders(): Customer? {
// Return a customer whose order count is the highest among all customers
return customers.maxBy { it.orders.size }
}复制代码
查找已购买价格最高的Product
fun Customer.getMostExpensiveOrderedProduct(): Product? {
// Return the most expensive product which has been ordered
return orderedProducts.maxBy { it.price }
}复制代码
18. n18Sort
通过Customer
的Order
数量排序
fun Shop.getCustomersSortedByNumberOfOrders(): List<Customer> {
// Return a list of customers, sorted by the ascending number of orders they made
return customers.sortedBy { it.orders.size }
}复制代码
sortedBy
为从小到大,sortedByDescending
为从大到小
19. n19Sum
统计已下订单总价,需要注意的是,一个Customer
可能多次购买了同一Product
fun Customer.getTotalOrderPrice(): Double {
// Return the sum of prices of all products that a customer has ordered.
// Note: a customer may order the same product for several times.
return orders.sumByDouble { it.products.sumByDouble { it.price } }
}复制代码
也可以
fun Customer.getTotalOrderPrice(): Double {
// Return the sum of prices of all products that a customer has ordered.
// Note: a customer may order the same product for several times.
return orders.flatMap { it.products }.sumByDouble { it.price }
}复制代码
20. n20GroupBy
分组
fun Shop.groupCustomersByCity(): Map<City, List<Customer>> {
// Return a map of the customers living in each city
return customers.groupBy { it.city }
}复制代码
21. n21Partition
获取未交付Order
数量多于已交付Order
的Customer
集合
fun Shop.getCustomersWithMoreUndeliveredOrdersThanDelivered(): Set<Customer> {
// Return customers who have more undelivered orders than delivered
return customers.filter {
val (delivered,undelivered) = it.orders.partition { it.isDelivered }
undelivered.size>delivered.size
}.toSet()
}复制代码
22. n22Fold
获取所有Customer
都购买了的Product
fun Shop.getSetOfProductsOrderedByEveryCustomer(): Set<Product> {
// Return the set of products ordered by every customer
return customers.fold(allOrderedProducts, {
orderedByAll, customer ->
orderedByAll.intersect(customer.orders.flatMap { it.products }.toSet())
})
}复制代码
flod
是一个类似reduce
的函数,该函数可以把前一次计算的返回值当成下一次计算的参数,flod
可以设置初始值,intersect
方法的意思是求交集
23. n23CompoundTasks
获取订购了某Product
的Customer
集合
fun Customer.getMostExpensiveDeliveredProduct(): Product? {
// Return the most expensive product among all delivered products
// (use the Order.isDelivered flag)
return orders.filter { it.isDelivered }.flatMap { it.products }.maxBy { it.price }
}复制代码
获取某Product
被购买的次数
fun Shop.getNumberOfTimesProductWasOrdered(product: Product): Int {
// Return the number of times the given product was ordered.
// Note: a customer may order the same product for several times.
return customers.flatMap { it.orders.flatMap { it.products } }.count { it==product }
}复制代码
24. n24ExtensionsOnCollections
用Kotlin
重写_24_JavaCode
中的doSomethingStrangeWithCollection
方法
fun doSomethingStrangeWithCollection(collection: Collection<String>): Collection<String>? {
val groupsByLength = Maps.newHashMap<Int, List<String>>()
for (s in collection) {
var strings: MutableList<String>? = groupsByLength[s.length] as MutableList<String>?
println(s)
if (strings == null) {
strings = Lists.newArrayList()
groupsByLength.put(s.length, strings)
}
strings!!.add(s)
}
var maximumSizeOfGroup = 0
for (group in groupsByLength.values) {
if (group.size > maximumSizeOfGroup) {
maximumSizeOfGroup = group.size
}
}
for (group in groupsByLength.values) {
if (group.size == maximumSizeOfGroup) {
return group
}
}
return null
}复制代码
第二节完,好多东西一知半解