kotlin 集合操作

1. set

fun testSet() {
    val set = setOf(1, 2, 3, 4)
    val set2 = setOf(4, 2, 3, 1)
    // 当两个set大小相同,一个set中每一个元素都在另一个set,则连个set相等
    println(set == set2) // true
    // set的默认实现是LinkedHashSet ,会保留元素插入的顺序
    // 另一种实现HashSet不存顺序,只需要较少内存存储相同数量的元素
}

2. map

fun testMap() {
    // map无论顺序,如果 key-value 的键值对都相等,两个map相等
    val map = mapOf("key1" to 1, "key2" to 2, "key3" to 3)
    val map2 = mapOf("key2" to 2, "key1" to 1, "key3" to 3)
    println(map == map2) // true

    // 默认实现LinkedHashMap,迭代时保留元素的插入顺序
    map2.keys.forEach {
        println("$it to ${map2[it]}") // key2, key1, key3
    }

    // HashMap 不会保留插入顺序
    val map3 = HashMap(3)
    map3["key2"] = 2
    map3["key1"] = 9
    map3["key3"] = 3
    map3.keys.forEach {
        println("$it to ${map3[it]}")// key1, key2, key3
    }
}

4. filter :过滤

// list.filterTo(list2) 是将list filter后的结果存入list2
fun testFilter() {
    val numbers = (1..7).toList().filter { it > 3 }
    println(numbers)  // [4, 5, 6, 7]
}

5. mapIndexed、 mapNotNull :List 转 List

fun testMapIndexed() {
    // .map 无法获取下标, .mapIndexed 可以获取到下标
    val numbers = (1..7).toList().mapIndexed { index, value -> value * index }
    println(numbers) // [0, 2, 6, 12, 20, 30, 42]
}

// 把null过滤掉
fun testMapNotNull() {
    val list = listOf(0, 1, 2, null, 4, 5, 6, 7, 4)
    val list2 = list.mapNotNull { it }
    println(list2) // [0, 1, 2, 4, 5, 6, 7, 4]
}

6. associate : List 转 Map

fun testAssociation() {
    val numbers = listOf("one", "two", "three", "four")
    // associateWith 生成的map,key 是元素本身,value 是花括号里的表达式
    println(numbers.associateWith { it.length })
    // associate 生成的map ,key value均可指定
    println(numbers.associate { it.length to it })
    // associateBy 生成的map key 是花括号里的表达式, value是元素本身
    println(numbers.associateBy { it.length })
}

7. zip :两个List 转 List

// 两集合相同位置的元素组成pair
fun testZip() {
    val colors = listOf("yellow", "red", "brown")
    val animals = listOf("dog", "fox", "bear")
    println(colors zip animals) // [(yellow, dog), (red, fox), (brown, bear)]
}

8. flatten :List 转 List

// flatten 将集合中的集合取出来
fun testFlat() {
    val list = listOf(listOf(1, 2, 3), listOf(4, 5, 6, 1, 2, 3), listOf(7, 8, 9))
    println(list.flatten()) // [1, 2, 3, 4, 5, 6, 1, 2, 3, 7, 8, 9]
    println(list.flatMap { it.asReversed() }) // [3, 2, 1, 3, 2, 1, 6, 5, 4, 9, 8, 7]
}

9. joinToString :List 转 String

fun testJoinToString() {
    val list = listOf("One", "Two", "Three")
    println(list.joinToString("/")) // One/Two/Three
    println(list.joinToString("/") { it.toUpperCase() }) //  ONE/TWO/THREE
}

10. partition :List 转 两个List

// 将list按条件分成两部分
fun testPartition() {
    val list = (0..10).toList()
    val (match, rest) = list.partition { it > 5 }
    println(match) // [6, 7, 8, 9, 10]
    println(rest) // [0, 1, 2, 3, 4, 5]
}

11. any、none、all

fun testAnyNoneAll() {
    val list = (0..10).toList()
    // 只要任意一个元素大于9
    println(list.any { it > 9 }) // true
    // 没有一个元素大于10
    println(list.none { it > 10 }) // true
    // 所有元素小于100
    println(list.all { it < 100 }) // true
}

12. 集合做加减法

// 两个集合做加减法
fun testPlusMinus() {
    val list = (0..10).toList()
    val list2 = (6..15).toList()
    println(list.plus(list2))
    // minus 减去list中的list2的元素
    println(list.minus(list2))
}

// 对于 mutableList :
// +=
fun testAdd() {
    val list = (0..10).toMutableList()
    list += 11
    list += listOf(12, 13, 14)
    println(list)
}

// -= 、 retainAll
fun testRemove() {
    val list = (0..10).toMutableList()
    // >5 的不删除
    println(list.retainAll { it > 5 }) // true
    println(list) // [6, 7, 8, 9, 10]
    list -= 6
    list -= listOf(7, 8)
    println(list) // [9, 10]
}

13. groupBy :List 转 Map>

fun testGroup() {
    val students = listOf(
        Student("s1", "c1"), Student("s2", "c1"),
        Student("s3", "c1"), Student("s21", "c2"), Student("s22", "c2")
    )
    // groupBy 返回一个map, key为classroomId, value 为List
    val studentGroup = students.groupBy { it.classroomId }
    println(studentGroup)
}

14. take、drop :List 转 List

fun testTakeAndDrop() {
    val list = (0..10).toList()
    // 取前5个元素
    println(list.take(5))
    // 取后5个元素
    println(list.takeLast(5))
    // 不取前5个
    println(list.drop(5))
    // 不取后5个
    println(list.dropLast(5))
    // 从第一个元素开始,取到不满足 it < 4 的第一个元素为止(不会取到不满足条件的那个元素)
    println(list.takeWhile { it < 4 })
    // 从不满足条件的元素开始,取到最后
    println(list.dropWhile { it < 4 })
}

15. chunked : List 转 List

// chunked(size) : 返回一个List,该List的元素也是list,每个list大小为size(最后一个不一定)
fun testChunked() {
    val list = (0..10).toList()
    val listChunked = list.chunked(3) // [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10]]
    println(listChunked)
    // 后加lambda表达式
    println(list.chunked(3) { it.sum() }) // [3, 12, 21, 19]
}

16. windowed : List 转 List窗口滑动

// 窗口滑动,不好说明,运行一次就懂了。。。
fun testWindowed() {
    val list = (0..10).toList()
    println(list.windowed(3))
    println(list.windowed(size = 3, partialWindows = true))
    println(list.windowed(3, step = 2))
    // [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10]]
    // [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10], [9, 10], [10]]
    // [[0, 1, 2], [2, 3, 4], [4, 5, 6], [6, 7, 8], [8, 9, 10]]
}

17. elementAtOrNull 当越界时返回null, getOrElse()、getOrNull

fun testElementAt() {
    val list = (0..3).map { it }
    println(list.elementAtOrNull(2)) // 2
    println(list.elementAtOrNull(4)) // null
}

18. first、last找不到元素会报错,使用firstOrNull、lastOrNull找不到返回空

fun testFirst() {
    val list = (0..3).map { it }
    println(list.firstOrNull { it > 4 }) // null
    println(list.first { it > 4 }) // 抛异常
}

19. random()随机取元素 list.random()

20. sorted()、sortedDescending()是按自然顺序排序

fun testSorted() {
    val list = listOf(5, 3, 1, 7, 9, 11, 0)
    println(list.sorted()) // [0, 1, 3, 5, 7, 9, 11]
    println(list.sortedDescending()) // [11, 9, 7, 5, 3, 1, 0]
    val listString = listOf("zz", "abc", "ab", "abcdefg", "cde")
    println(listString.sorted()) // [ab, abc, abcdefg, cde, zz]
    println(listString.sortedDescending()) // [zz, cde, abcdefg, abc, ab]
}

21. sortedBy() 自定义顺序

fun testSortedBy() {
    val list = listOf(1, 9, 4, 2, 7, 3, 8)
    println(list.sortedBy { it % 2 == 0 }) // [1, 9, 7, 3, 4, 2, 8]
}

22. sortedWith() 自定义

fun testSortedWith() {
    val list = listOf(1, 9, 4, 2, 7, 3, 8)
    println(
        list.sortedWith(
            compareBy({ it % 2 == 0 }, { it }) // [1, 3, 7, 9, 2, 4, 8]
        )
    )
list.sortedWith(
                // 排序规则:按点评分数降序,如果分数相同,则按提交时间升序
                Comparator { s1, s2 ->
                    if (s1.value == s2.value) {
                        s1.submitHomeworkTime.compareTo(s2.submitHomeworkTime)
                    } else {
                        s2.value - s1.value
                    }
                }
        )
}


23. mutable 的 sort() 是对原数组进行排序

fun testSort() {
    val list = mutableListOf(1, 3, 2, 5, 4)
    list.sort()
    println(list)
}

24. 集合随机排序

fun testShuffled() {
    val list = listOf(5, 3, 1, 7, 9, 11, 0)
    println(list.shuffled())
}

25. min() , max(), average(), sum(), count(), minBy(), minWith(), sumBy()

26. 二分查找

fun testBinarySearch() {
    var list = listOf(1, 3, 2, 5, 6, 4, 7, 8)
    list = list.sorted()
    println(list)
    println(list.indexOf(5))
    println(list.binarySearch(5))
}

27. fill 用某元素填满列表

fun testFill() {
    val list = (0..10).toMutableList()
    list.fill(11)
    println(list)
}

28. 集合的并集、交集、补集, List也可用,只不过返回结果也是set

fun testSetAction() {
    val set = setOf(1, 2, 3, 4, 5)
    // 并集
    println(set union setOf(3, 4, 5, 6, 7)) // [1, 2, 3, 4, 5, 6, 7]
    // 交集
    println(set intersect setOf(3, 4, 5, 6, 7)) // [3, 4, 5]
    // 补集
    println(set subtract setOf(3, 4, 5, 6, 7)) // [1, 2]
}

你可能感兴趣的:(kotlin 集合操作)