Các function đặc biệt trong Kotlin Collections

Các function sử dụng với Collection Kotlin cung cấp khá nhiều function của các Collection rất hữu ích và tiện dụng, tuy nhiên có những function mà có khi chúng ta còn chưa động đến hoặc chưa biết đến. Vậy thì chúng ta sẽ cùng lướt qua xem nhé. 1. Tạo collection mới Tất cả

Các function sử dụng với Collection

Kotlin cung cấp khá nhiều function của các Collection rất hữu ích và tiện dụng, tuy nhiên có những function mà có khi chúng ta còn chưa động đến hoặc chưa biết đến. Vậy thì chúng ta sẽ cùng lướt qua xem nhé.

1. Tạo collection mới

Tất cả các function dưới đây đều được sử dụng để khởi tạo các loại collection khác nhau:

  • Empty Collection: emptyList, emptyMap, emptySet
  • Read-only Collection: listOf, mapOf, setOf
  • Mutable Collection: mutableListOf, mutableMapOf, mutableSetOf
  • Build Collection: buildList, buildMap, buildSet
  • Sorted Collection: sortedMapOf, sortedSetOf (xem thêm ở stackOverflow)
  • Hash Collection: hashMapOf, hashSetOf (xem thêm ở stackOverflow)

Ví dụ:

val simpleList =listOf("someString","someOtherString")val simpleMap =mapOf(1to"first",2to"second",3to"third")val simpleSet =setOf("someUniqueString","someOtherUniqueString","sameString","sameString")****val mutableList =mutableListOf("someString","someOtherString")val mutableMap =mutableMapOf(1to"first",2to"second",3to"third")val mutableSet =mutableSetOf("someUniqueString","someOtherUniqueString","sameString","sameString")

2. Convert sang loại Collection khác

Tất cả các function dưới đây đều được sử dụng để convert từ loại collection hiện tại sang loại collection khác

  • Convert thành Array: toBooleanArray, toByteArray, toCharArray, toDoubleArray, toFloatArray, toIntArray, toLongArray, toShortArray, toTypedArray, toUByteArray, toUIntArray, toULongArray, toUShortArray
  • Convert thành read-only collection: toList, toMap, toSet
  • Convert thành mutable collection: toMutableList, toMutableMap, toMutableSet, toHashSet
  • Convert thành sorted collection: toSortedMap, toSortedSet

Ví dụ:

val simpleList =listOf("someString","someOtherString")val mutableList =mutableListOf("someString","someOtherString")val newMutableList = simpleList.toMutableList()val newSimpleList = mutableList.toList()

3.Thay đổi data của Collection

Tất cả các function dưới đây đều được sử dụng để thay đổi data của collection.

Thêm và xóa data

  • Set data: set, setValue
  • Thêm data: plus, plusElement, plusAssign,add, addAll, put, putAll
  • Xóa data: minus, minusElement, minusAssign, remove
  • Xóa data ở đầu hoặc cuối collection: drop, dropLast, dropLastWhile, dropWhile,
    removeFirst, removeFirstOrNull, removeLast, removeLastOrNull, take, takeLastWhile, takeLast, takeWhile
  • Lấy phần tử ở giữa collection: slice, sliceArray
  • Lấy những phần tử duy nhất: distinct, distinctBy

Ví dụ:

val simpleList =listOf("someString","someOtherString")val mutableList =mutableListOf("someString","someOtherString")val mutableMap =mutableMapOf(1to"first",2to"second",3to"third")val mutableSet =mutableSetOf("someUniqueString","someOtherUniqueString","sameString","sameString")val addedSimpleList = simpleList.plus("SomeNewElement")

mutableList.add("SomeNewElement")
mutableSet.addAll(simpleList)
mutableMap.remove(1)
mutableMap.put(1,"A new String to replace the old one")
mutableSet.minus("someUniqueString")
mutableList.dropLast(2)
mutableList.slice(1..2)
mutableList.distinct()

Biến đổi giá trị các phần tử

  • Biến đổi giá trị các phần tử: map, mapTo, mapIndexed, mapIndexedTo, mapKeys, mapKeysTo, mapValues, mapValuesTo, replaceAll, fill
  • Biến đổi các phần tử đồng thời loại bỏ các giá trị null: mapNotNull, mapNotNullTo, mapIndexedNotNull, mapIndexedNotNullTo

Ví dụ:

val mappedMutableList = simpleList.map{ texts -> texts +"someFunnyEnding"}val lengthOfStrings = simpleList.map{ texts -> texts.length }

Lọc các phần tử

  • Lọc: filter, filterIndexed, filterIndexedTo, filterIsInstance, filterIsInstanceTo, filterKeys, filterNot, filterNotNull, filterNotNullTo, filterNotTo, filterTo, filterValues

Ví dụ:

val stringsWithLessThan12Letters = simpleList.filter{ texts -> texts.length<12}val textsContainingAWord = simpleList.filter{ it.contains("some")}

Sắp xếp các phần tử

  • Sắp xếp theo thứ tự: sorted, sortedArray, sortedArrayDescending, sortedArrayWith, sortedBy, sortedByDescending, sortedDescending, sortedWith sort, sortBy, sortByDescending, sortDescending, sortWith
  • Sắp xếp random: shuffle, shuffled

Nguồn tham khảo: https://medium.com/geekculture/kotlin-special-functions-in-collections-9f91bbd9dca6

Nguồn: viblo.asia

Bài viết liên quan

Những ngành nghề AI có thể thay thế dần trong tương lai.

Những ngành nghề AI có thể thay thế trong tương lai gần Dựa trên các báo cáo và

Tạo Subdomain miễn phí với is-a.dev 🤪

Cuối tuần mọi người thế nào, mình thì rảnh quá lướt Facebook, tớ tình cờ th

Dùng TailwindCSS v4 trong SpringBoot + JTE

Giới thiệu JTE là gì? JTE (Java Template Engine) là một template engine an toàn, nhẹ và

WebGL và Three.js cho hệ thống thử đồ ảo

Giới thiệu Với sự phát triển nhanh chóng của thương mại điện tử, kỳ vọng