Kotlin-集合List Set Map

List
有序集合,只读List,可变MutableList。分别通过listOf()和mutableListOf()创建

// 可变集合
val systemUsers: MutableList<Int> = mutableListOf(1, 2, 3)        // 1
// 通过类型转化,sudoers变为只读集合
val sudoers: List<Int> = systemUsers                              // 2

fun addSystemUser(newUser: Int) {                                 // 3
    systemUsers.add(newUser)                      
}

fun getSysSudoers(): List<Int> {                                  // 4
    return sudoers
}

fun main() {
    addSystemUser(4)                                              // 5 
    println("Tot sudoers: ${getSysSudoers().size}")               // 6
    getSysSudoers().forEach {                                     // 7
        i -> println("Some useful info on user $i")
    }
    // getSysSudoers().add(5) <- Error!                           // 8
}

Set
无序集合,只读Set,可变MutableSet。分别通过setOf()和mutableSetOf()创建

val openIssues: MutableSet<String> = mutableSetOf("uniqueDescr1", "uniqueDescr2", "uniqueDescr3") // 1

fun addIssue(uniqueDesc: String): Boolean {                                                       
    return openIssues.add(uniqueDesc)                                                             // 2
}

fun getStatusLog(isAdded: Boolean): String {                                                       
    return if (isAdded) "registered correctly." else "marked as duplicate and rejected."          // 3
}

fun main() {
    val aNewIssue: String = "uniqueDescr4"
    val anIssueAlreadyIn: String = "uniqueDescr2" 

    println("Issue $aNewIssue ${getStatusLog(addIssue(aNewIssue))}")                              // 4
    println("Issue $anIssueAlreadyIn ${getStatusLog(addIssue(anIssueAlreadyIn))}")                // 5 
}

Map
key value
通过 mapOf() 和 mutableMapOf() 创建

val EZPassAccounts: MutableMap<Int, Int> = mutableMapOf(Pair(1,100), Pair(2,100), Pair(3,100))
简便方式: A to B

val EZPassAccounts: MutableMap<Int, Int> = mutableMapOf(1 to 100, 2 to 100, 3 to 100)

to 的内部实现是中缀函数

public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)
const val POINTS_X_PASS: Int = 15
val EZPassAccounts: MutableMap<Int, Int> = mutableMapOf(1 to 100, 2 to 100, 3 to 100)   // 1
val EZPassReport: Map<Int, Int> = EZPassAccounts                                        // 2

fun updatePointsCredit(accountId: Int) {
    if (EZPassAccounts.containsKey(accountId)) {                                        // 3
        println("Updating $accountId...")                                               
        EZPassAccounts[accountId] = EZPassAccounts.getValue(accountId) + POINTS_X_PASS  // 4
    } else {
        println("Error: Trying to update a non-existing account (id: $accountId)")
    } 
}

fun accountsReport() {
    println("EZ-Pass report:")
    EZPassReport.forEach {                                                              // 5
        k, v -> println("ID $k: credit $v")
    }
}

fun main() {
    accountsReport()                                                                    // 6
    updatePointsCredit(1)                                                               // 7
    updatePointsCredit(1)                                                               
    updatePointsCredit(5)                                                               // 8 
    accountsReport()                                                                    // 9
}

只读集合没有add方法,可变集合有add方法
继承关系

List Set

public interface Iterable<out T> {
    public operator fun iterator(): Iterator<T>
}

public interface MutableIterable<out T> : Iterable<T>

public interface Collection<out E> : Iterable<E>

public interface MutableCollection<E> : Collection<E>, MutableIterable<E>

public interface List<out E> : Collection<E>
public interface MutableList<E> : List<E>, MutableCollection<E>

public interface Set<out E> : Collection<E>
public interface MutableSet<E> : Set<E>, MutableCollection<E>

Map:

public interface Map<K, out V>
public interface MutableMap<K, V> : Map<K, V>

集合方法:

在这里插入图片描述

操作函数 filter map

val numbers = listOf(1, -2, 3, -4, 5, -6)      
val positives = numbers.filter { x -> x > 0 }  
val negatives = numbers.filter { it < 0 }      
println("positives = $positives negatives = $negatives")

val doubled = numbers.map { x -> x * 2 }      
val tripled = numbers.map { it * 3 }          
println("doubled = $doubled tripled = $tripled")

操作函数 any, all, none
any 集合中至少有一个满足判断条件
all 集合中每一个元素都满足判断条件
none 集合中没有一个元素满足判断条件

al numbers = listOf(1, -2, 3, -4, 5, -6)            // 1
val anyNegative = numbers.any { it < 0 }             // 2
val anyGT6 = numbers.any { it > 6 }    

val allEven = numbers.all { it % 2 == 0 }            // 2
val allLess6 = numbers.all { it < 6 }                // 3

val allEven = numbers.none { it % 2 == 1 }           // 2
val allLess6 = numbers.none { it > 6 }               // 3

操作函数 find, findLast

find 返回满足条件的第一个元素 没有返回null
findLast 返回满足条件的最后一个元素,没有返回null

val words = listOf("Lets", "find", "something", "in", "collection", "somehow")

val first = words.find { it.startsWith("some") }     // something
val last = words.findLast { it.startsWith("some") }  // somehow

val nothing = words.find { it.contains("nothing") }  // null

操作函数 first, last
first() 返回集合中的第一个元素
last() 返回集合中的最后一个元素

first{} 返回集合中满足条件的第一个元素
last{} 返回集合中满足条件的最后一个元素

val numbers = listOf(1, -2, 3, -4, 5, -6)            // 1

val first = numbers.first()                          // 2
val last = numbers.last()                            // 3

val firstEven = numbers.first { it % 2 == 0 }        // 4
val lastOdd = numbers.last { it % 2 != 0 }           // 5

操作函数 firstOrNull, lastOrNull
firstOrNull() 返回集合中的第一个元素 集合为空返回null
lastOrNull() 返回集合中的最后一个元素 集合为空返回null

firstOrNull{} 返回满足条件的集合中的第一个元素
lastOrNull{} 返回满足条件的集合中的最后一个元素

val words = listOf("foo", "bar", "baz", "faz")         // 1
val empty = emptyList<String>()                        // 2

val first = words.firstOrNull()                        // 3
val last = empty.lastOrNull()                          // 4

val firstF = words.firstOrNull { it.startsWith('f') }  // 5
val firstZ = words.firstOrNull { it.startsWith('z') }  // 6
val lastF = words.lastOrNull { it.endsWith('f') }      // 7
val lastZ = words.lastOrNull { it.endsWith('z') }      

操作函数
count() 返回集合数,count{}或者满足条件的集合数
associateBy 将list转化为Map<K,V>类型的集合 value为匹配集合中最后一个
groupBy 将list转化为Map<K, List>类型的集合 value为匹配集合

data class Person(val name: String, val city: String, val phone: String) // 1

val people = listOf(                                                     // 2
    Person("John", "Boston", "+1-888-123456"),
    Person("Svyatoslav", "Saint-Petersburg", "+7-999-456789"),
    Person("Sarah", "Munich", "+49-777-789123"),
    Person("Vasilisa", "Saint-Petersburg", "+7-999-123456"))

// key = phone value = {person,person}
val phoneBook = people.associateBy { it.phone }                          // 3
// key = phone value = city
val cityBook = people.associateBy(Person::phone, Person::city)           // 4
// key = city  value = [name,name]
val peopleCities = people.groupBy(Person::city, Person::name)            // 5
// key = city value = name (city有两个相等的,取最有一个city对应的name = Vasilisa)
val lastPersonCity = people.associateBy(Person::city, Person::name)
结果:lastPersonCity = {Boston=John, Saint-Petersburg=Vasilisa, Munich=Sarah}  

partition 根据条件将原集合拆分为2个集合。
第一个集合满足条件
第二个集合不满足条件

源码:
public inline fun <T> Iterable<T>.partition(predicate: (T) -> Boolean): Pair<List<T>, List<T>> {
    val first = ArrayList<T>()
    val second = ArrayList<T>()
    for (element in this) {
        if (predicate(element)) {
            first.add(element)
        } else {
            second.add(element)
        }
    }
    return Pair(first, second)
}
val numbers = listOf(1, -2, 3, -4, 5, -6)                // 1

val evenOdd = numbers.partition { it % 2 == 0 }           // 2
val (positives, negatives) = numbers.partition { it > 0 } // 3

println("Numbers: $numbers")
println("Even numbers: ${evenOdd.first}")
println("Odd numbers: ${evenOdd.second}")
println("Positive numbers: $positives")
println("Negative numbers: $negatives")

flatMap 把原集合List<List>放到一个新集合List中并返回
主要是Iterable类型的集合

源码:
public inline fun <T, R> Iterable<T>.flatMap(transform: (T) -> Iterable<R>): List<R> {
    return flatMapTo(ArrayList<R>(), transform)
}

public inline fun <T, R, C : MutableCollection<in R>> Iterable<T>.flatMapTo(destination: C, transform: (T) -> Iterable<R>): C {
    for (element in this) {
        val list = transform(element)
        destination.addAll(list)
    }
    return destination
}
 val fruitsBag = listOf("apple","orange","banana","grapes")  // 1
 val clothesBag = listOf("shirts","pants","jeans")           // 2
 val cart = listOf(fruitsBag, clothesBag)                    // 3
 val mapBag = cart.map { it }                                // 4
 val flatMapBag = cart.flatMap { it } 
 
cart or mapBag : [[apple, orange, banana, grapes], [shirts, pants, jeans]]
flatMapBag : [apple, orange, banana, grapes, shirts, pants, jeans]
    

minOrNull, maxOrNull 返回最小值,最大值

sorted 按照自然顺序进行排序,默认是升序
sortedBy 按照给定条件进行排序
sortedDescending sortedByDescending 通过比较器进行排序

zip 中缀函数,将两个集合的每个元素拼接,然后组成一个新的集合,

public infix fun <T, R> Iterable<T>.zip(other: Iterable<R>): List<Pair<T, R>> {
    return zip(other) { t1, t2 -> t1 to t2 }
}
val A = listOf("a", "b", "c")                  // 1
val B = listOf(1, 2, 3, 4)                     // 1

val resultPairs = A zip B                      // 2
val resultReduce = A.zip(B) { a, b -> "$a$b" } // 3
println("resultPairs: $resultPairs, resultReduce = $resultReduce")

resultPairs: [(a, 1), (b, 2), (c, 3)], resultReduce = [a1, b2, c3]

getOrElse 根据索引获取当前值,没有给一个默认值

val list = listOf(0, 10, 20)
println(list.getOrElse(1) { 42 })    // 1
println(list.getOrElse(10) { 42 })   // 2

结果:
10
42
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值