用Kotlin-koans学Kotlin【三】ii_collections

本节主要介绍了Kotlin标准库中提供的对于集合的扩展,都是非常实用强大的功能

我们通过为Shop类编写各种功能的扩展来练习这部分功能,测试数据在对应测试目录下的TestShop.kt

13. n13Introduction

获取ShopCustomer的集合

fun Shop.getSetOfCustomers(): Set<Customer> {
    return customers.toSet()
}复制代码
14. n14FilterMap

Kotlin为集合扩展了filtermap,forEach等等方法,这些在Java中称为Steram Api,功能都是相似的,但是无疑Kotlin用起来更方便
本练习要求我们获取所有CustomserCity,并放到一个Set中,还有获取来自某一个City的所有CustomerList

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 }
}复制代码

统计来自某一CityCustomer的数量

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

通过CustomerOrder数量排序

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数量多于已交付OrderCustomer集合

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

获取订购了某ProductCustomer集合

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
}复制代码

第二节完,好多东西一知半解

转载于:https://juejin.im/post/59e453d16fb9a0452724a3fa

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值