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

7 Cách Tăng Tốc Ứng Dụng React Hiệu Quả Mà Bạn Có Thể Làm Ngay

React là một thư viện JavaScript phổ biến trong việc xây dựng giao diện người d

Trung Quốc “thả quân bài tẩy”: hàng loạt robot hình người!

MỘT CUỘC CÁCH MẠNG ROBOT ĐANG HÌNH THÀNH Ở TRUNG QUỐC Thượng Hải, ngày 13/5 –

9 Mẹo lập trình Web “ẩn mình” giúp tiết kiệm hàng giờ đồng hồ

Hầu hết các lập trình viên (kể cả những người giỏi) đều tốn thời gian x

Can GPT-4o Generate Images? All You Need to Know about GPT-4o-image

OpenAI‘s GPT-4o, introduced on March 25, 2025, has revolutionized the way we create visual con