博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用Kotlin-koans学Kotlin【三】ii_collections
阅读量:6280 次
发布时间:2019-06-22

本文共 5861 字,大约阅读时间需要 19 分钟。

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

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

13. n13Introduction

获取ShopCustomer的集合

fun Shop.getSetOfCustomers(): Set
{ return customers.toSet()}复制代码

14. n14FilterMap

Kotlin为集合扩展了filtermap,forEach等等方法,这些在Java中称为Steram Api,功能都是相似的,但是无疑Kotlin用起来更方便

本练习要求我们获取所有CustomserCity,并放到一个Set中,还有获取来自某一个City的所有CustomerList

fun Shop.getCitiesCustomersAreFrom(): Set
{ return customers.map { it.city }.toSet()}复制代码
fun Shop.getCustomersFrom(city: City): List
{ // 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
get() { // Return all products this customer has ordered return orders.flatMap { it.products }.toSet()}复制代码

获取Shop卖出的Product集合

val Shop.allOrderedProducts: Set
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
{ // 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
> { // Return a map of the customers living in each city return customers.groupBy { it.city }}复制代码

21. n21Partition

获取未交付Order数量多于已交付OrderCustomer集合

fun Shop.getCustomersWithMoreUndeliveredOrdersThanDelivered(): Set
{ // 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
{ // 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
): Collection
? { val groupsByLength = Maps.newHashMap
>() for (s in collection) { var strings: MutableList
? = groupsByLength[s.length] as MutableList
? 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

你可能感兴趣的文章
IOE,为什么去IOE?
查看>>
java 用反射简单应用,将Object简单转换成map
查看>>
Storm中的Worker
查看>>
dangdang.ddframe.job中页面修改表达式后进行检查
查看>>
Web基础架构:负载均衡和LVS
查看>>
Linux下c/c++相对路径动态库的生成与使用
查看>>
SHELL实现跳板机,只允许用户执行少量允许的命令
查看>>
SpringBoot 整合Redis
查看>>
2014上半年大片早知道
查看>>
Android 6.0指纹识别App开发案例
查看>>
正文提取算法
查看>>
轻松学PHP
查看>>
Linux中的网络监控命令
查看>>
this的用法
查看>>
windows下安装redis
查看>>
CentOS7 yum 安装git
查看>>
启动日志中频繁出现以下信息
查看>>
httpd – 对Apache的DFOREGROUND感到困惑
查看>>
分布式锁的一点理解
查看>>
idea的maven项目,install下载重复下载本地库中已有的jar包,而且下载后jar包都是lastupdated问题...
查看>>