Kotlin编程实践5章 集合

集合

1、使用数组

arrayOf ,并使用Array类中的属性与方法来处理他们内部的值
java中:

String [] strings = new String[4];
strings[0] = "an";
strings[1] = "array";
strings[2] = "of";
strings[3] = "strings";
//或者
strings = "an array of strings".split(" ");

kotlin中:

val strings = arrayOf("this","is","an","array","of","strings")

arrayOfNulls创建仅包含空值的数组,必须指定类型

val nullStringArray = arrayOfNulls(5)//一个仅仅包含空值的数组

Array类

val squares = Array(5){i -> (i*i).toString()}
//结果为{"0","1","4","9","16"}的数组

withIndex访问数组

val strings = arrayOf("this","is","an","array","of","strings")
for((index,value) in strings.withIndex()){
    pringln("Index $index maps to $value")
}

Index 0 maps to this
Index 1 maps to is
Index 2 maps to an
Index 3 maps to array
Index 4 maps to of
Index 5 maps to strings

2、创建集合

不可变的集合:listOf、setOf、mapOf
可变版本:mutableListOf、mutableSetOf、mutableMapOf

var numList = listOf(3,1,4,1,5,9)
var numSet = setOf(3,1,4,1,5,9)//numSet.size == 5
var map = mapOf(1 to "one",2 to "two",3 to "three")

var numList = mutableListOf(3,1,4,1,5,9)
var numSet = mutableSetOf(3,1,4,1,5,9)
var map = mutableMapOf(1 to "one",2 to "two",3 to "three")

3、为已存在的集合创建只读视图

如何为现有可变list/map/set创建只读版本。
将值赋值给List、Set、Map即可

val muNums = mutableListOf(3,1,4,1,5,9)

val onlyReadNum :List = muNums .toList()

该方法创建了一个单独的对象,内容相同但不代表是相同对象。
如果想要一个相同对象的只读视图,将可变list赋值给一个List类的引用即可:

val readOnlySameList :List = muNums 

如果指向的list被修改,只读视图也会显示修改后的值。

4、从集合构建map

如何通过每个键生成,键值关联起来的map?
associateWith函数

val keys = 'a'..'f'
val map = key.associateWith{it to it.toString().repeat(5).capitalize()}
println(map)

{a=(a, Aaaaa), b=(b, Bbbbb), c=(c, Ccccc), d=(d, Ddddd), e=(e, Eeeee), f=(f, Fffff)}
//如果是老版本的kotlin输出如下
{a=Aaaaa, b=Bbbbb, c=Ccccc, d=Ddddd, e=Eeeee, f=Fffff}

在kotlin 1.3中的associateWith简化了代码,生成了String值,而不是生成Pair

val keys = 'a'..'f'
val map = key.associateWith{it.toString().repeat(5).capitalize()}
println(map)

{a=Aaaaa, b=Bbbbb, c=Ccccc, d=Ddddd, e=Eeeee, f=Fffff}

5、当集合为空的时候返回默认值

使用ifEmpty 和ifBlank

data class Product(val name:String,
                  val price:Double,
                   val onSale:Boolean = false)
//     val products = listOf(pA,pB,pC)
val products = listOfNotNull()
println(nameOfP1(products))

 fun nameOfP1(products :List) = 
        products.filter{it.onSale}
            .map{it.name}
            .joinToString(separator = ",")
            
fun nameOfP2(products :List) = 
        products.filter{it.onSale}
            .map{it.name}
            .ifEmpty{listOf("none")}  //默认空集合
            .joinToString(separator = ",")
            
fun nameOfP3(products :List) = 
        products.filter{it.onSale}
            .map{it.name}
            .joinToString(separator = ",")
            .ifEmpty{"none"}  //默认空字符串

1结果只是换行了
23结果会输出none

6、将变量限制在给定区间

给定一个值,在区间内返回本身,在区间外返回最小值和最大值。
使用coerceIn函数,并传入最小值和最大值。

    val range = 3..8
    println(5.coerceIn(range))  //5
    println(5.coerceIn(3,8))    //5
    
    println(1.coerceIn(range))  //3
    println(1.coerceIn(3,8))    //3

7、处理集合中的窗口

chunked:将集合切分为相同部分
windowed:将块沿集合滑动给定间隔的块

chunked,切分集合为一个包含list的list,每个列表都具有给定大小或更小

fun main() {
    val range = 0..10
    val chunked = range.chunked(3)
    println("chunked="+chunked)

//chunked=[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]]

    val chunked2 = range.chunked(3){it.average()}
    println("chunked2="+chunked2)
//chunked2=[1.0, 4.0, 7.0, 9.5]
}

chunked函数其实是windowed函数的特殊情况
windowed函数接收3个函数 size(每个窗口的元素数量)、step(每一步向前移动的元素数,默认1)、partialwindows(默认false,如果没有足够数量,是否保留最后一部分)

chunked(size:Int) ->return windowed(size,size,true)

8、解构list

解构是通过将对象的值分配给变量的集合来从中提取值的过程。

val list = listOf("a","b","c","d","e","f","g")
val (a,b,c,d,e) = list
println("$a $b $c $d $e")
//a b c d e

列表创建的前五个元素已经分配给了相同名称变量。之所以可行是因为List类具有名为componentN的标准库中定义的扩展函数,其中N从1到5.

9、将多个属性排序

sortedWith / compareBy

data class Golfer(val score:Int,val first:String,val last:String)

fun main() {   
    val golfers = listOf(
        Golfer(70,"jack","nicklaus"),
        Golfer(68,"tom","watson"),
        Golfer(68,"bubba","watson"),
        Golfer(70,"tiger","woods"),
        Golfer(68,"ty","webb"),
    )

    //score > lastname > first name
    val sorted = golfers.sortedWith(
        compareBy({it.score},{it.last},{it.first})
    )
    sorted.forEach{println(it)}
}
->
Golfer(score=68, first=bubba, last=watson)
Golfer(score=68, first=tom, last=watson)
Golfer(score=68, first=ty, last=webb)
Golfer(score=70, first=jack, last=nicklaus)
Golfer(score=70, first=tiger, last=woods)

另一种方式是使用thenBy

val comparator = compareBy(Golfer::score)
    .thenBy(Golfer::last)
    .thenBy(Golfer::first)

golfers.sortedWith(comparator )
    .forEach(::printLn)

10、自定义迭代器

11、根据类型过滤集合

filterIsInstance / filterIsInstanceTo

kotlin集合中包含一个filter的扩展函数,接受一个可以用来提取满足任何布尔条件的元素谓词作为参数

val list = listOf("a",LocalDate.now(),3,1,4,"b")
val strings = list.filter{it is String}

for(s in strings){
    s.length//不编译,类型被删除
}

尽管过滤有效,但推定类型为List因此不会转换为String.
可以添加filterIsInstance

val list = listOf("a",LocalDate.now(),3,1,4,"b")

val all= list.filterIsInstance()
val strings= list.filterIsInstance()
val ints= list.filterIsInstance()
val datas= list.filterIsInstance()

all -> list
strings ->"a","b"
ints - > 1,3,4
dates -> LocalDate.now()

filterIsInstance 返回类型是List
filterIsInstanceTo返回类型是MutableCollection

val list = listOf("a",LocalDate.now(),3,1,4,"b")

val all= list.filterIsInstanceTo(mutableListOf())
val strings= list.filterIsInstanceTo(mutableListOf())
val ints= list.filterIsInstanceTo(mutableListOf())
val datas= list.filterIsInstanceTo(mutableListOf())

12、在数列中创建区间

kotlin使用双点操作符可以创建区间如1..5,创建一个IntRange。kotlin的区间都是闭区间,即包含两个端点。

import java.time.LocalDate
fun main() {
    val started = LocalDate.now()
    val mid = started.plusDays(3)
    val end = started.plusDays(5)
    
    val dataRange = started..end

    println(started in dataRange)//t
    println(mid in dataRange)//t
    println(end in dataRange)//t
    println(started.minusDays(1) in dataRange)//f
}

一旦尝试在区间进行迭代,会有编译错误

for(date in dateRange) println(it)//编译错误

问题在于区间而不在于数列,自定义数列实现了iterable接口
需要自定义Iterator,接口覆盖next和hasNext

你可能感兴趣的:(Kotlin编程实践5章 集合)