本节主要介绍了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
}第二节完,好多东西一知半解