Kotlin learning (7) collections

Kotlin container is set on the basis of the Java, was modified and extended, it introduced immutable collections , while expanding a number of convenient and practical features.

Further, not only can hold objects Koltin common collection classes, but also holds a function of the type of variable .
The following example is a collection class holds two functions:

//声明一个持有类型为 (Int)->Boolean的List,元素为两个函数
val funlist: List<(Int) -> Boolean> = listOf({ it -> it % 2 == 0 }, { it -> it % 2 ==1})

And this time, we will be able to choose which code inside the function call

val list = listOf(1, 2, 3, 4, 5, 6, 7)
list.filter(funlist[0])     //传入第一个函数funlist[0],返回[2,4,6]
list.filter(funlist[1])     //传入第二个函数funlist[1],返回[1,3,5,7]

7.1 collection class inheritance hierarchy

Overview of collections is not talked about, primarily Set, Map, List three sets.
And their inheritance hierarchy and Java is almost the same, but there are some differences:

Here Insert Picture Description
Here are a few categories:

  • MutableIterable
    during the iterative support iteration delete elements
  • Collection
    Read-only is not writable
  • MutableCollection
    support for adding and removing elements of the Collection interface elements and orderly, as well as add, remove and other functions
  • List
    of elements Ordered, read-only can not write
  • MutableList
    addition to List function has read data, as well as add, clear, remove write functions, etc.
  • Set
    read-only is not writable

Summary
can be seen, some sets are writable, some collections are not written.
For example, List is divided into read-only Listand read-write MutableList, Set, too
and although no successor Map Collection, but it is also divided into read-only Mapand read-writeMutableMap

7.2 Creating collections

Kotlin respectively using listOf(), setOf(), mapOf()function to create immutable List, Set, Map container
use mutableListOf(), mutableSetOf(), mutableMapOf()function to create respectively MutableList, MutableSet, MutableMap container.

val list = listOf(1, 2, 3, 4, 5, 6, 7)     //创建不可变list
val list1 = mutableListOf("A", "B", "C")   //创建可变list

If no elements to create an empty List, you can use listOf, but this time we must declare the parameter type:

//这样声明是会报错的
val emptyList = listOf()
//正确姿势
val emptyList<Int> = listOf()

7.3 traversing elements in the collection

List, Set class inherits from the Iterable interface, which extends the forEach function to iterate through the elements, Mao interface is also extended forEach

list.forEach{
   println(it)
}

set.forEach{
   println(it)
}

map.forEach{
    println("key = ${it.key}, value = ${it.value}")
}

In addition, if we want to access the index subscript when traversing elements, and can be used in the Set List forEachIndexed()

list.forEachIndexed {  index, value  -> println("list index = ${index}, value = ${value} ")

set.forEachIndexed{ index, value -> println("set index = ${index} , value = ${value}")}
}

7.4 mapping function

Using the map function, elements of a set can be sequentially performed using a mapping operation to a particular transfer function, then the new value will be mapped into elements of a new set, and returns the new collection.
Here Insert Picture Description
In List, Set, and Map interfaces inherited Iterable interface, provides the map function. Examples are as follows:

val list = listOf(1, 2, 3, 4, 5, 6, 7)
val set = setOf(1, 2, 3, 4, 5, 6, 7)
val map = mapOf(1 to "a", 2 to "b", 3 to "c")

list.map{ it * it}       //返回[1, 4, 9, 25, 36, 49]
set.map{ it + 1}         //返回[2, 3, 4, 5, 6, 7, 8]
map.map{ it.value + "$"}  //返回[a$, b$, c$]

We can also pass on more than just the map function, it can also be a data type, such as we pass a list:

val strList = listOf("a", "b", "c")
strlist.map{ it -> listOf(it + 1, it + 2, it + 3, it + 4) }

This time, the return type, i.e. a nested inside a List List, the above code returns the following results:

//嵌套List
[[a1, a2, a3, a4], [b1, b2, b3, b4], [c1, c2, c3, c4]] 

Kotlin also provides an flatten()effect is the nested structure List "tiled" into a layer structure. code show as below:

//"平铺"函数,把嵌套在List中的元素"平铺"成一层List
strlist.map{ it -> listOf(it +1, it + 2, it +3, it +4) }.flatten()

Output is as follows:

[a1, a2, a3, a4, b1, b2, b3, b4, c1, c2, c3, c4]

When flatMap function "composite logical" map flat and two functions, the following sample code:

strlist.flatMap { it -> listOf(it + 1, it + 2, it + 3, it + 4) }

//输出:
[a1, a2, a3, a4, b1, b2, b3, b4, c1, c2, c3, c4]

7.5 filter function

We have previously studied the filter (), here cite a code sample, first of all, there is a Student object, we use the data class to the following statement:

data class Student(var id:Long, var name: String, var age: Int, var score: Int){}


val studentList = listOf(
   Student(1, "Java", 20, 100)
   Student(2, "Kotlin", 10, 80)
   Student(3, "Python", 19, 95)
 )

This time, if we want to filter out students older than 19, the code can be written:

studentList.filter{ it.age >= 19}

If filtered through access index, may be used filterIndexed()

val list = listOf(1, 2, 3, 4, 5, 6, 7)
list.filterIndexed{ index, it -> index % == 0 &&  it > 3}

//输出
[5, 7]

7.6 Sorting Function

Kotlin collection class provides a set of function elements in reverse order reversed()

val list = listOf(1, 2, 3, 4, 5, 6, 7)
val set = setOf(1, 3, 2)

list.reversed()    //倒序函数,返回[7, 6, 5, 4, 3, 2, 1]
set.reversed()     //返回 (2, 3,1)

When ascending sort function sorted(),

list.sorted()    //返回[1, 2, 3, 4, 5, 6, 7]
set.sorted()     //返回[1, 2, 3]

7.7 elements to weight

If we want to list the elements of a List deduplication can be called directly distinct()

val dupList = listOf(1, 1, 2, 2, 3, 3, 3)
dupList.distinct()              //返回 [1, 2, 3]
Published 248 original articles · won praise 99 · Views 100,000 +

Guess you like

Origin blog.csdn.net/rikkatheworld/article/details/102958999