用Kotlin-koans學Kotlin【三】ii_collections

HankeXu發表於2017-10-16

本節主要介紹了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
}複製程式碼

第二節完,好多東西一知半解

相關文章