dir.by  
Поиск >>

Компьютер, программы
→
Kotlin
 Lists in Kotlin: interface List , interface MutableList , class ArrayList. Functions to create: listOf(...), mutableListOf(...), arrayListOf(...) 
посмотрели 2041 раз
обновлено: 24 September 2026
  Kotlin  
interface List<E>
interface List<E> is an array (in other words, a collection of elements).
Any element can be gotten by integer index.
You cannot add or delete elements.

Description:
  Kotlin     library kotlin-stdlib.jar Collections.kt file
interface List<E> : Collection<E> {
Let's look at Functions >> ...
}

 
To create List<E>, use the function: listOf(...)
  Kotlin     Example
class Car (val name:String, val price:Int)
{
}

...

// Create List
val allCars:List<Car> = listOf(
     Car("Audi A6", 50000),
     Car("Toyota Camry", 25000),
     Car("Honda Accord", 40000)
)

// We find cars whose price > 20000
val foundItems = allCars.filter { elem ->
     elem.price>20000
}

// Going through all the elements
foundItems.forEach { elem ->
     // show car name and car price on the screen
     println("${elem.name} ${elem.price}")
}
  Kotlin  
interface MutableList<E>
interface MutableList<E> is an array (in other words, a collection of elements).
Any element can be gotten by integer index.
You can add and remove elements using the add, remove functions.

Description:
  Kotlin     library kotlin-stdlib.jar Collections.kt file
interface MutableList<E> : List<E>, MutableCollection<E> {
Let's look at Functions >> ...
}

 
To create MutableList<E>, use the function: mutableListOf(...)
  Kotlin     Example
class Car (val name:String, val price:Int)
{
}

...

// Create MutableList
val allCars:MutableList<Car> = mutableListOf(
     Car("Audi A6", 50000),
     Car("Toyota Camry", 25000),
     Car("Honda Accord", 40000)
)

allCars.add( Car("Kia Sorento", 32000) )
allCars.add( Car("Hyundai Tucson", 34000) )

allCars.removeIf{elem ->
     elem.name=="Honda Accord"
}

// We find cars whose price > 20000
val foundItems = allCars.filter { elem ->
     elem.price>20000
}

// Going through all the elements
foundItems.forEach { elem ->
     // show car name and car price on the screen
     println("${elem.name} ${elem.price}")
}
  Kotlin  
class ArrayList<E>
class ArrayList<E> is an array (in other words, a collection of elements).
Any element can be gotten by integer index.
You can add and remove elements using the add, remove functions.

Note!
There is NO class ArrayList <E>in the Kotlin library
Kotlin The library contains only the title. This name references the Java library.
  Kotlin     TypeAliases.kt file
typealias class ArrayList<E>               = java.util.ArrayList<E>


Description:
  Java     Library java.util file ArrayList.java
class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
{
Let's look at Functions >> ...
}

 
To create ArrayList<E>, use the function: arrayListOf(...)
  Kotlin     Method 1
val allCars:ArrayList<Car> = arrayListOf(
     Car("Audi A6", 50000),
     Car("Toyota Camry", 25000),
     Car("Honda Accord", 40000)
)


Another way to create we can use constructor ArrayList:
  Kotlin     Method 2
val allCars:ArrayList<Car> = ArrayList<Car>(
     listOf(
          Car("Audi A6", 50000),
          Car("Toyota Camry", 25000),
          Car("Honda Accord", 40000)
     )
)
Functions listOf(...), mutableListOf(...), arrayListOf(...)
Function
return
Implementation
  Kotlin  
listOf(...)
  Kotlin  
List<T>
  Java  
java.util.ArrayList
  Kotlin  
mutableListOf(...)
  Kotlin  
MutableList<T>
  Java  
java.util.ArrayList
  Kotlin  
arrayListOf(...)
  Kotlin  
ArrayList<T>
  Java  
java.util.ArrayList
Why create ArrayList ?
Answer: As a general rule, you should always give preference to the interface.
Therefore, interface MutableList should be used.
Examples, all interface functions MutableList
Create
mutableListOf(7, 35, 14)
function creates a list and within 3 items
Note! Any number of elements can be written at the time of creation
  Kotlin     Example 1
val myList1:MutableList<Int> = mutableListOf(7, 35, 14)
// myList1 = 7, 35, 14


  Kotlin     Example 2
val myList1:MutableList<Int> = mutableListOf(10, 20, 30, 40, 50, 60)
// myList1 = 10, 20, 30, 40, 50, 60
mutableListOf()
The function creates an empty list
  Kotlin     Example
val myList1:MutableList<Int> = mutableListOf()
// myList1 = 0 elements
number of elements
size
The field contains the number of elements
  Kotlin     Example
val myList1:MutableList<Int> = mutableListOf(7, 35, 14)

val n:Int = myList1.size
// n = 3
isEmpty()
The function returns true if the list is empty
  Kotlin     Example 1
val myList1:MutableList<Int> = mutableListOf()

val myListEmpty:Boolean = myList1.isEmpty()
// myListEmpty = true


  Kotlin     Example 2
val myList1:MutableList<Int> = mutableListOf(7, 35, 14)

val myListEmpty:Boolean = myList1.isEmpty()
// myListEmpty = false
Converting a collection to
map{element -> object of new type}
Convert a collection to a different type of element
  Kotlin     Example

class Car (val name:String, val price:Int)
{
}

class Book (val author:String)
{
}

...

val allCars:MutableList<Car> = mutableListOf(
     Car("Audi A6", 50000),
     Car("Toyota Camry", 25000),
     Car("Honda Accord", 40000)
)

// Convert a collection of Car elements to Book elements
val convertedItems:List<Book> = allCars.map {elem -> Book(elem.name) }

Functions: toList()   toSet()   toMutableList()   toSortedSet()   toTypedArray()
View items, search for items
get(index)
Selecting an element by position
index it is a position starting from 0
 
 
 
 
You can do it like this:
[index]
  Kotlin     Example 1
val myList1:MutableList<Int> = mutableListOf(7, 35, 14, 9)

val element = myList1.get(2)
// element = 14


  Kotlin     Example 2
val myList1:MutableList<Int> = mutableListOf(7, 35, 14, 9)

val element = myList1[2]
// element = 14
find{element -> conditions}
finding one element by conditions
The function returns the
If not found, return null
  Kotlin     Example
val myList1:MutableList<Int> = mutableListOf(7, 35, 14, 9)

val foundValue = myList1.find{ value -> value==14 || value==7 }
// foundValue = 7

val foundValue = myList1.find{ value -> value==97 }
// foundValue = null
filter{element -> conditions}
Select elements by condition.
A new list is created.
  Kotlin     Example
val myList1:MutableList<Int> = mutableListOf(7, 35, 14, 9)

// Select elements where the values are greater than 10
val myList2 = myList1.filter { value -> value>10 }
// myList2 = 35, 14     This is a new list
// myList1 = 7, 35, 14, 9     The old list has not changed
subList(indexStart, indexEnd)
Select the elements from the starting to the final position.
A new list is created.
Note! No element is taken in the final position.
  Kotlin     Example
val myList1:MutableList<Int> = mutableListOf(7, 35, 14, 9, 82)

// Select the elements, from 1 to 3 positions
val myList2 = myList1.subList(1, 3)
// myList2 = 35, 14     This is a new list
// myList1 = 7, 35, 14, 9, 82     The old list has not changed
forEach{element -> Action}
Go through all the elements.
  Kotlin     Example
val myList1:MutableList<Int> = mutableListOf(7, 35, 14, 9)

myList1.forEach { value ->
     // Displaying the value on the screen
     println(value)
}
Other functions: single()   elementAtOrElse()   elementAtOrNull()   first()   firstOrElse()   firstOrNull()   take()
replace element
set(index, element)
replace element at the position with the specified element
index it is a position
  Kotlin     Example
val myList1:MutableList<Int> = mutableListOf(7, 35, 14, 9)

// For position 2, put the number 130
myList1.set(2, 26)
// myList1 = 7,         35,         130,               9
//         index=0     index=1   index=2     index=3
Other functions: fill()
Adding Items
add(element)
adding one element to the end
  Kotlin     Example
val myList1:MutableList<Int> = mutableListOf(7, 35)

myList1.add(10)
// myList1 = 7, 35, 10
addAll(array)
adding array of elements to the end

addAll(collection)
adding collection of elements to the end
  Kotlin     Example 1
val myList1:MutableList<Int> = mutableListOf(7, 35)

val values:Array<Int> = arrayOf(210, 160, 14)
myList1.addAll(values)
// myList1 = 7, 35, 210, 160, 14


  Kotlin     Example 2
val myList1:MutableList<Int> = mutableListOf(7, 35)

val myList2:Collection<Int> = listOf(400,300,200)
myList1.addAll(myList2)
// myList1 = 7, 35, 400, 300, 200

add(index, element)
adding one element at the specified position
index it is a position
  Kotlin     Example
val myList1:MutableList<Int> = mutableListOf(7, 35, 14, 9)

// At position 2, add the number 26
myList1.add(2, 26)
// myList1 = 7,         35,         26,             14,            9
//          index=0    index=1   index=2     index=3    index=4
addAll(index, collection)
adding collection of elements at the specified position
  Kotlin     Example
val myList1:MutableList<Int> = mutableListOf(10, 20, 30)

val values:Collection<Int> = listOf(500,600)
myList1.addAll(1, values)
// myList1 = 10, 500, 600, 20, 30
Other functions: addFirst()   addLast()   plus()
Deleting Items
remove(element)
deleting one element, even if element duplicating
  Kotlin     Example
val myList1:MutableList<Int> = mutableListOf(7, 35, 14, 7, 21)

val isDeleted = myList1.remove(7)
// isDeleted = true
//myList1 = 35, 14, 7, 21
removeAt(index)
deleting by index
  Kotlin     Example
val myList1:MutableList<Int> = mutableListOf(7, 35, 14, 9)

val element = myList1.removeAt(1)
// element = 35
// myList1 = 7, 14, 9
removeAll(collection)
to delete only those elements that match the collection
  Kotlin     Example
val myList1:MutableList<Int> = mutableListOf(10, 20, 30)

val values:Collection<Int> = listOf(10, 30)
myList1.removeAll(values)
// myList1 = 20
retainAll(collection)
delete all elements but retain only those elements that match the collection
  Kotlin     Example
val myList1:MutableList<Int> = mutableListOf(10, 20, 30)

val values:Collection<Int> = listOf(10, 30)
myList1.retainAll(values)
// myList1 = 10, 30
clear()
deleting all elements
  Kotlin     Example
val myList1:MutableList<Int> = mutableListOf(7, 35, 14, 9)

val element = myList1.clear()
// myList1 = 0 elements
Other functions: removeFirst()   removeFirstOrNull()   removeLast()   removeLastOrNull()   removeIf()
sorting, filtering (selection of elements by condition), grouping and other algorithms
sortBy{element -> Sort field}
sorting all elements
  Kotlin     Example
val myList1:MutableList<Int> = mutableListOf(7, 35, 14, 9)

// Sorting Ascending
myList1.sortBy { value -> value }
// myList1 = 7, 9, 14, 35

// Sorting Descending
myList1.sortBy { value -> -value }
// myList1 = 35, 14, 9, 7
filter{element -> conditions}
Select elements by condition.
A new list is created.
  Kotlin     Example
val myList1:MutableList<Int> = mutableListOf(7, 35, 14, 9)

// Select elements where the values are greater than 10
val myList2 = myList1.filter { value -> value>10 }
// myList2 = 35, 14     This is a new list
// myList1 = 7, 35, 14, 9     The old list has not changed
Other functions: binarySearch   drop   subList()   retainAll{ }   replaceAll{ }   groupBy{ }   fold()   max()   min()   intersect()   slice()   sum()   average()   zip()   sortWith()   asReversed()   reverse()   reversed()   shuffle()   associateBy{ }   associateWith{ }   average()   chunked()   distinct()   random()   partition{ }
Validating a Collection
Functions: contains()   containsAll()   all()   any()
 
← Previous topic
Collections in Kotlin
 
Next topic →
Arrays in Kotlin: class Array<T>, class IntArray, class FloatArray. Functions to create: arrayOf(...), intArrayOf(...), floatArrayOf(...)
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

 
• What is Kotlin?
• Why is IntelliJ IDEA the most popular development environment for Kotlin?
• Download and install IntelliJ IDEA to explore Kotlin
• Create a new console project to explore Kotlin | IntelliJ IDEA
Setting the value
• Declare the variable and set the value in Kotlin | val, var, lateinit, constant: const val, global variable: companion object
null
• null value, use the symbol ? and ?. and !! and ?: and !!. and ?. in Kotlin
Int, Float, Boolean, Char ...
• Integer numbers in Kotlin are: Byte, UByte, Short, UShort, Int, UInt, Long, ULong
• Decimal numbers in Kotlin are: Float, Double
• A flag with values of true or false in Kotlin is: Boolean
• The symbol in Kotlin is: Char
• Convert number to text in Kotlin | Int → String
String
• The string, the text in Kotlin is: String
• Interpolate strings in Kotlin. Example: val address:String = "${street}, ${country}"
• What is the difference between String and StringBuilder ?
Enum
• What is an enumeration (enum) in Kotlin ?
• How do I find enum by value in Kotlin ?
Collections and Arrays
• Collections in Kotlin
• Lists in Kotlin: interface List , interface MutableList , class ArrayList. Functions to create: listOf(...), mutableListOf(...), arrayListOf(...)
• Arrays in Kotlin: class Array<T>, class IntArray, class FloatArray. Functions to create: arrayOf(...), intArrayOf(...), floatArrayOf(...)
Function
• fun() { ... } is a function in Kotlin. The function is needed to perform an action.
Extension function
• Extension function in Kotlin. Allows you to add a new function to the system (List, ..) or my (Book, ...) class
Lambda function
• Lambda function in Kotlin. Example 1: var myFunc1 : (a:Int, b:Int) -> Int = { p1, p2 -> p1 + p2 };
Class
• What is class in Kotlin? Example: class MyBook { ... } | Primary and secondary constructor | block init
• Access modifiers (private, protected, public) for a class and for methods and fields. | Kotlin
• lateinit is a late initialization for the class field | Kotlin
• class that inherits from interface in Kotlin | Example: class MyBook : IBook { ...}
• Unnamed class that inherits from interface in Kotlin | Example: val book1 = object : IBook { ...}
• Generic, template class in Kotlin | Example: class MyBook<T> { ... }
Flow
• flow is the data flow in Kotlin. These are the substitution of LiveData in Android Kotlin and the substitution of Observable in RxJava
Writing a program
• The Kotlin console app works like Android Jetpack Compose

  Ваши вопросы присылайте по почте: info@dir.by