映射函数: map{(T) -> R} 根据传入的转换函数将原有的集合转换成一个新的 List 集合
1 2 3 4 5 6
fun Shop.getCitiesCustomersAreFrom(): Set<City> { // Return the set of cities the customers are from returnthis.customers.map { it.city }.toSet() }
过滤函数: filter{(T) -> Boolean} 根据传入的判断函数返回一个新的 List 集合
1 2 3 4 5 6
fun Shop.getCustomersFrom(city: City): List<Customer> { // Return a list of the customers who live in the given city returnthis.customers.filter { it.city == city } }
val Customer.orderedProducts: Set<Product> get() { // Return all products this customer has ordered //返回用户全部订单中所有的商品种类 return orders.flatMap { it.products }.toSet() }
val Shop.allOrderedProducts: Set<Product> get() { // Return all products that were ordered by at least one customer //返回商店中全部的至少被一位用户下单过的商品 customers.flatMap { it.orders }.flatMap { it.products }.toSet()
fun Customer.getMostExpensiveOrderedProduct(): Product? { // Return the most expensive product which has been ordered return orders.flatMap { it.products //订单铺平成商品 }.maxBy { it.price //取出商品中价格最大的 } }
排序函数:sortedBy{} 根据传入的选择器升序排列
1 2 3 4 5 6
fun Shop.getCustomersSortedByNumberOfOrders(): List<Customer> { // Return a list of customers, sorted by the ascending number of orders they made returnthis.customers.sortedBy { it.orders.size //按照客户的订单数升序排列 } }
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. orders.flatMap { it.products }.sumByDouble { it.price }
orders.flatMap { it.products }.fold(0.0,{acc, product -> acc+product.price }) var result = 0.0 orders.flatMap { it.products }.forEach { result+=it.price } return result }
分组函数 groupBy{} 按照传入的选择器将集合对象分组返回Map<K, List<T>>
1 2 3 4 5 6 7 8 9 10 11 12 13 14
fun Shop.groupCustomersByCity(): Map<City, List<Customer>> { // fun Shop.groupCustomersByCity(): Map<City, List<Customer>> { // Return a map of the customers living in each city //不使用groupBy函数的写法 val map = mutableMapOf<City,List<Customer>>() val citys = this.customers.map { it.city }.toSet().map { map.put(it, this.getCustomersFrom(it)) } // return map //效果等同
fun Shop.getSetOfProductsOrderedByEachCustomer(): Set<Product> { // Return the set of products that were ordered by each of the customers //找到商店中每一个用户都下单的商品 allOrderedProducts.filter { p -> customers.all { it.orders.flatMap { it.products }.any { it == p } } }.toSet() return customers.fold(allOrderedProducts, { orderedByAll, customer -> //第一次调用该函数时传入值为fold函数的第一个参数 全部被下单的产品集合 orderedByAll.intersect( //交集运算 customer.orders.flatMap { it.products }.toSet() //传入的用户的全部产品的集合 ) }) }