Untitled
unknown
plain_text
2 years ago
10 kB
12
Indexable
kotlin.datastructure
3. lists
3.1. ForLoopAndList.kt
fun main() {
IteratingThroughAMutableList()
IteratingByIndexes()
IteratingByRangeIndexes()
}
fun IteratingThroughAMutableList() {
val daysOfWeek = mutableListOf("Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat")
for (day in daysOfWeek){
println(day)
}
}
fun IteratingByIndexes() {
val daysOfWeek = mutableListOf("Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat")
for (index in daysOfWeek.indices){
println("$index: ${daysOfWeek[index]}")
}
}
fun IteratingByRangeIndexes() {
val daysOfWeek = mutableListOf("Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat")
for (index in 1..5) {
println("$index: ${daysOfWeek[index]}")
}
for (index in daysOfWeek.lastIndex downTo 0 step 2) {
println("$index: ${daysOfWeek[index]}")
}
}
##############################
3.2. List.kt
/*
Pick a read-only List when you're working with a specific set of elements that shouldn't change.
*/
fun main() {
myList()
printlnList()
spreadOperator()
}
fun myList() {
val readOnlyList = listOf(1, 2, 3, 4, 5)
// readOnlyList[1] = 10 // Error
for (index in readOnlyList.indices) {
println("$index: ${readOnlyList[index]}")
}
println(readOnlyList.indexOf(2))
println(readOnlyList.joinToString())
val temp = listOf(1, 2, 3, 4, 5)
println(temp == readOnlyList)
println(readOnlyList.sum())
val copyList = readOnlyList.toList()
println(copyList.joinToString())
val myList = listOf<String>("Thieu", "Hien")
println(joinOptions(myList))
}
fun joinOptions(options: Collection<String>) =
options.joinToString(",", )
fun printlnList() {
val stringList = listOf("Thieu", "Hien", "Tung")
println(stringList)
println(stringList.joinToString())
}
fun spreadOperator() {
// Toan tu spread (*) dung de "trai" mot mang hoac mot danh sach thanh cac phan tu rieng le khi truyen doi so
// cho mot ham hoac mot danh sach
val array = arrayOf(1, 2, 3)
val list = listOf(-1, 0, *array, 4)
println(list) // [-1, 0, 1, 2, 3, 4]
println(listOf(-1, 0, array, 4)) // [-1, 0, [Ljava.lang.Integer;@20ad9418, 4]
fun foo(vararg strings: String) {
for (string in strings) {
println(string)
}
}
val strArr = arrayOf("a", "b", "c")
foo(strings = strArr)
foo(*strArr)
val intArray = intArrayOf(1, 2, 3) // IntArray khac Array<Int>
val intList = listOf(-1, 0, *intArray.toTypedArray(), 4)
}
######################################
3.3. MultiDimensionalList.kt
fun main() {
twoDimensionalLists()
}
fun twoDimensionalLists() {
var mutList2D = mutableListOf(
mutableListOf<Int>(0, 0, 0, 0),
mutableListOf<Int>(0, 0, 0, 0),
mutableListOf<Int>(0, 0, 0, 0)
)
mutList2D = mutableListOf(
mutableListOf<Int>(0, 1, 2), //[0]
mutableListOf<Int>(3, 4, 5) //[1]
)
println(mutList2D[0][0])
val mutListOfStringAndInt2D = mutableListOf(
mutableListOf<String>("Practice", "makes", "perfect"),
mutableListOf<Int>(1, 2)
)
println(mutListOfStringAndInt2D)
}
fun threeDimensionalLists() {
val mutList3D = mutableListOf(
mutableListOf(mutableListOf<Int>(0,1), mutableListOf<Int>(2,3)),
mutableListOf(mutableListOf<Int>(4,5), mutableListOf<Int>(6,7))
)
println(mutList3D) // [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]
}
#######################################
3.4. MutableList.kt
import java.util.*
/*
A MutableList is a collection capable of holding a list of elements and allows modification of its contents.
This implies that elements can be added, removed, or updated anytime.
Key Differences:
1. Mutability:
MutableList lets you make changes after it's created.
The immutable list (for example, listOf) can only be read, not modified.
2. Functions:
MutableList includes functions such as add, remove, and clear.
These functions are not available for the immutable list.
*/
fun main() {
// commonOperations()
// batchOperations()
modifyingLists()
}
fun commonOperations() {
val list = mutableListOf(1, 2, 3)
// add
list.add(4) // list becomes [1, 2, 3, 4]
// add at index
list.add(1, 5) // list becomes [1, 5, 2, 3, 4]
// remove
list.remove(5) // list becomes [1, 2, 3, 4]
// removeAt
list.removeAt(0) // list becomes [2, 3, 4]
// set
list.set(1, 10) // list becomes [2, 10, 4]
list[1] = 10
// clear
list.clear() // list becomes []
}
fun iteration() {
val mutableList = mutableListOf("apple", "banana", "cherry")
for (item in mutableList) {
println(item)
}
mutableList.forEach { item ->
println(item)
}
}
fun batchOperations() {
val mutableList = mutableListOf("apple", "banana", "cherry")
// map
val lengths = mutableList.map { it.length }
// filter
val longFruits = mutableList.filter { it.length > 5 }
// for each
mutableList.forEach { println(it.uppercase()) }
}
fun modifyingLists() {
val mutableList = mutableListOf("apple", "banana", "cherry")
mutableList.replaceAll { it.uppercase(Locale.getDefault()) }
mutableList.forEach { println(it) }
val upperCaseList = mutableList.map { it.uppercase(Locale.getDefault()) }
mutableList.clear()
mutableList.addAll(upperCaseList)
}
###########################################
fun main() {
// outputtingAList()
}
fun outputtingAList() {
val southernCross = mutableListOf("Acrux", "Gacrux", "Imai", "Mimosa")
println(southernCross.joinToString()) // Acrux, Gacrux, Imai, Mimosa
println(southernCross.joinToString(" -> ")) // Acrux -> Gacrux -> Imai -> Mimosa
println(southernCross.joinToString(" "))
println(southernCross.joinToString(""))
}
fun multipleLists() {
// Join
val southernCross = mutableListOf("Acrux", "Gacrux", "Imai", "Mimosa")
val stars = mutableListOf("Ginan", "Mu Crucis")
val newList = southernCross + stars
println(newList.joinToString()) // Acrux, Gacrux, Imai, Mimosa, Ginan, Mu Crucis
// Compare
val firstList = mutableListOf("result", "is", "true")
val secondList = mutableListOf("result", "is", "true")
val thirdList = mutableListOf("result")
println(firstList == secondList) // true
println(firstList == thirdList) // false
println(secondList != thirdList) // true
}
fun copyListContent() {
val list = mutableListOf(1, 2, 3, 4, 5)
val copyList = list.toMutableList()
print(copyList) // [1, 2, 3, 4, 5]
val list2 = mutableListOf(1, 2, 3, 4, 5)
val copyList2 = mutableListOf<Int>()
copyList2.addAll(list2)
print(copyList2) // [1, 2, 3, 4, 5]
}
fun otherUsefulFunction() {
val list = mutableListOf(1, 2, 3, 4, 5)
// check whether the list is empty.
list.isEmpty()
list.isNotEmpty()
// creates a smaller list (sublist)
val subList = list.subList(1, 4) // [2, 3, 4]
// searches for the index of an element in the list.
if (5 in list) {
println(list.indexOf(5)) // 4
}
print(list.indexOf(7)) // -1
// search for the minimum and maximum elements in the list.
list.minOrNull()
list.maxOrNull()
// the sum of the elements in the list.
list.sum()
// build a sorted list (ascending or descending) from the available list.
list.sorted()
list.sortedDescending()
}
##################################
4. variables
4.1. Equality.kt
fun main() {
}
fun comparison() {
val msg1 = "Hi"
val msg2 = "Hi"
// Structural equality
print(msg1 == msg2) // msg1 and msg2 have the same state
print(msg1 == "Hello")
// Referential equality
val blueBox = Box(3) // box with 3 balls
val azureBox = blueBox
println(blueBox == azureBox ) // true, it's a copy
blueBox.addBall() // add a ball to the first box
println(blueBox == azureBox ) // true, the second box also contains 4 balls
}
fun referenceEquality() {
// Kotlin provides a special operator === to check if the variables point to the same object.
val blueBox = Box(3)
val azureBox = blueBox
val cyanBox = Box(3)
println(blueBox == azureBox) // true
println(blueBox === azureBox) // true, azureBox points to the same object
println(blueBox == cyanBox) // true
println(blueBox === cyanBox) // false, cyanBox points to another object
print(blueBox !== cyanBox) // true
blueBox.addBall()
println(blueBox == cyanBox) // false
var two = 2
var anotherTwo = 2
println(two === anotherTwo) // true
}
class Box(private var ball: Int = 0) {
fun getBall(): Int {
return ball
}
fun addBall() {
ball++
}
}
##################################
4.2. Variables.kt
/*
* val (for value) declares a read-only variable
* var (for variable) declares a mutable variable
* The value of a const variable is known at compile time and won't be changed at runtime
*/
const val CONST_DOUBLE = 3.14 // const can duoc khoi tao o top-level, ben ngoai function
fun main() {
val language = "Kotlin"
var dayOfWeek = "Monday"
// dayOfWeek = 11; //Error
val myMutableList = mutableListOf(1, 2, 3, 4, 5)
// mot bien val khong dong nghia voi bat bien (immutable)
// bien val khong cho phep gan lai nhung duoc phep sua doi noi dung trong no!
myMutableList.add(6)
println(myMutableList)
var `good name` = 5
`good name` = 6
}
class MyClass {
companion object {
const val CONST_INT = 127
const val MY_STRING = "This is a constant string"
// const val STRING = readln() // not a constant String!!!
// const val CONST_ARRAY = arrayOf(1, 2, 3) // error: only primitives and strings are allowed
}
}
3.5. WorkWithMutableList.kt
Editor is loading...
Leave a Comment