0% found this document useful (0 votes)
41 views14 pages

List in Kotlin

The document discusses various operations that can be performed on lists in Kotlin like creating immutable and mutable lists, indexing, iterating, sorting, filtering, mapping, adding, subtracting and slicing lists. It also covers methods like contains(), isEmpty(), indexOf(), get() etc.

Uploaded by

a7813010
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views14 pages

List in Kotlin

The document discusses various operations that can be performed on lists in Kotlin like creating immutable and mutable lists, indexing, iterating, sorting, filtering, mapping, adding, subtracting and slicing lists. It also covers methods like contains(), isEmpty(), indexOf(), get() etc.

Uploaded by

a7813010
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

List in Kotlin

A list is a generic ordered collection of elements. Kotlin has two types of lists, immutable
lists (cannot be modified) and mutable lists (can be modified).
Read-only lists are created with listOf() whose elements cannot be modified and mutable
lists created with mutableListOf() method where we alter or modify the elements of the list.
Kotlin program of list contains Integers –

fun main(args: Array<String>) {


val a = listOf('1', '2', '3')
println(a.size)
println(a.indexOf('2'))
println(a[2])
}
Output:
3
1
3

Kotlin program of list contains Strings –

fun main(args: Array<String>) {


//creating list of strings
val a = listOf("Ram", "Shyam", "Raja", "Rani")
println("The size of the list is: "+a.size)
println("The index of the element Raja is: "+a.indexOf("Raja"))
println("The element at index "+a[2])
for(i in a.indices){
println(a[i])
}
}

Output:

The size of the list is: 4


The index of the element Raja is: 2
The element at index Raja
Ram
Shyam
Raja
Rani
Indexing of Elements of List in Kotlin –
Each element of a list has an index. The first element has an index of zero (0) and the
last Element has index len – 1, where ‘len’ is the length of the list.
fun main(args: Array<String>)
{
val numbers = listOf(1, 5, 7, 32, 0, 21, 1, 6, 10)
val num1 = numbers.get(0)
println(num1)
val num2 = numbers[7]
println(num2)
val index1 = numbers.indexOf(1)
println("The first index of number is $index1")
val index2 = numbers.lastIndexOf(1)
println("The last index of number is $index2")

val index3 = numbers.lastIndex


println("The last index of the list is $index3")
}

Output:

1
6
The first index of number is 0
The last index of number is 6
The last index of the list is 8

First and Last Elements –


We can retrieve the first and the last elements of the list without using the get()
method.

fun main(args: Array<String>){


val numbers = listOf(1, 5, 7, 32, 0, 21, 1, 6, 10)
println(numbers.first())
println(numbers.last())
}

Output:

1
10
List Iteration methods –
It is process of accessing the elements of list one by one.
There are several ways of doing this in Kotlin.

fun main(args: Array<String>)


{
val names = listOf("Gopal", "Asad", "Shubham", "Aditya", "Devarsh", "Nikhil", "Gagan")
// method 1
for (name in names) {
print("$name, ")
}
println()
// method 2
for (i in 0 until names.size) {
print("${names[i]} ")
}
println()

// method 3
names.forEachIndexed({i, j -> println("names[$i] = $j")})

// method 4
val it: ListIterator<String> = names.listIterator()
while (it.hasNext()) {
val i = it.next()
print("$i ")
}
println()
}

Output:
Gopal, Asad, Shubham, Aditya, Devarsh, Nikhil, Gagan,
Gopal Asad Shubham Aditya Devarsh Nikhil Gagan
names[0] = Gopal
names[1] = Asad
names[2] = Shubham
names[3] = Aditya
names[4] = Devarsh
names[5] = Nikhil
names[6] = Gagan
Gopal Asad Shubham Aditya Devarsh Nikhil Gagan
Explanation:

for (name in names) {


print("$name, ")
}

The for loop traverses the list. In each cycle, the variable ‘name’ points to the next
element in the list.

for (i in 0 until names.size) {


print("${names[i]} ")
}

This method uses the size of the list. The until keyword creates a range of the list
indexes.

names.forEachIndexed({i, j -> println("namess[$i] = $j")})

With the forEachIndexed() method, we loop over the list having index and value
available in each iteration.

val it: ListIterator = names.listIterator()


while (it.hasNext()) {
val i = it.next()
print("$i ")
}

Here we use a ListIterator to iterate through the list.

Sorting the elements in list –


The following example show how to sort a list in ascending or descending order.
fun main(args: Array<String>)
{
val list = listOf(8, 4, 7, 1, 2, 3, 0, 5, 6 )
val asc = list.sorted()
println(asc)
val desc = list.sortedDescending()
println(desc)
}
Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8]
[8, 7, 6, 5, 4, 3, 2, 1, 0]

Explanation:
val asc = list.sorted()

The sorted() method sorts the list in ascending order.

val desc = list.sortedDescending()

The sortedDescending() method sorts the list in descending order.

Contains() and containsAll() functions –


This method checks whether an element exists in the list or not.

fun main(args: Array<String>)


{
val list = listOf(8, 4, 7, 1, 2, 3, 0, 5, 6 )

val res = list.contains(0)

if (res)
println("The list contains 0")
else
println("The list does not contain 0")

val result = list.containsAll(listOf(3, -1))

if (result)
println("The list contains 3 and -1")
else
println("The list does not contain 3 and -1")
}

Output:

The list contains 0


The list does not contain 3 and -1
Explanation:
val res = list.contains(0)

Checks whether the list contains 0 or not and returns true or false (her true) that is
stored in res.

val result = list.containsAll(listOf(3, -1))

Checks whether the list contains 3 and -1 or not.

The "in" Operator

The in operator can be used to check the existence of an element in a list.

Example
fun main() {
val theList = listOf("one", "two", "three", "four")

if("two" in theList){
println(true)
}else{
println(false)
}
}

When you run the above Kotlin program, it will generate the following output:
true

The contain() Method


The contain() method can also be used to check the existence of an element in a list.

Example
fun main() {
val theList = listOf("one", "two", "three", "four")

if(theList.contains("two")){
println(true)
}else{
println(false)
}

}
When you run the above Kotlin program, it will generate the following output:

true

The isEmpty() Method

The isEmpty() method returns true if the collection is empty (contains no elements),
false otherwise.

Example
fun main() {
val theList = listOf("one", "two", "three", "four")

if(theList.isEmpty()){
println(true)
}else{
println(false)
}
}

When you run the above Kotlin program, it will generate the following output:

false

The indexOf() Method

The indexOf() method returns the index of the first occurrence of the specified
element in the list, or -1 if the specified element is not contained in the list.

Example
fun main() {
val theList = listOf("one", "two", "three", "four")

println("Index of 'two' : " + theList.indexOf("two"))


}

When you run the above Kotlin program, it will generate the following output:

Index of 'two' : 1
The get() Method
The get() method can be used to get the element at the specified index in the list.
First element index will be zero.

Example
fun main() {
val theList = listOf("one", "two", "three", "four")

println("Element at 3rd position " + theList.get(2))


}

When you run the above Kotlin program, it will generate the following output:

Element at 3rd position three

List Addition
We can use + operator to add two or more lists into a single list. This will add second
list into first list, even duplicate elements will also be added.
Example
fun main() {
val firstList = listOf("one", "two", "three")
val secondList = listOf("four", "five", "six")
val resultList = firstList + secondList

println(resultList)
}
When you run the above Kotlin program, it will generate the following output:
[one, two, three, four, five, six]
List Subtraction
We can use - operator to subtract a list from another list. This operation will remove
the common elements from the first list and will return the result.

Example
fun main() {
val firstList = listOf("one", "two", "three")
val secondList = listOf("one", "five", "six")
val resultList = firstList - secondList
println(resultList)
}
When you run the above Kotlin program, it will generate the following output:

[two, three]

Slicing a List

We can obtain a sublist from a given list using slice() method which makes use of
range of the elements indices.

Example
fun main() {
val theList = listOf("one", "two", "three", "four", "five")
val resultList = theList.slice( 2..4)

println(resultList)
}

When you run the above Kotlin program, it will generate the following output:

[three, four, five]

Removing null a List

We can use filterNotNull() method to remove null elements from a Kotlin list.

fun main() {
val theList = listOf("one", "two", null, "four", "five")
val resultList = theList.filterNotNull()

println(resultList)
}

When you run the above Kotlin program, it will generate the following output:

[one, two, four, five]

Filtering Elements

We can use filter() method to filter out the elements matching with the given
predicate.

fun main() {
val theList = listOf(10, 20, 30, 31, 40, 50, -1, 0)
val resultList = theList.filter{ it > 30}

println(resultList)
}

When you run the above Kotlin program, it will generate the following output:

[31, 40, 50]

Dropping First N Elements

We can use drop() method to drop first N elements from the list.

fun main() {
val theList = listOf(10, 20, 30, 31, 40, 50, -1, 0)
val resultList = theList.drop(3)

println(resultList)
}

When you run the above Kotlin program, it will generate the following output:

[31, 40, 50, -1, 0]

Grouping List Elements

We can use groupBy() method to group the elements matching with the given
predicate.

fun main() {
val theList = listOf(10, 12, 30, 31, 40, 9, -3, 0)
val resultList = theList.groupBy{ it % 3}

println(resultList)
}

When you run the above Kotlin program, it will generate the following output:

{1=[10, 31, 40], 0=[12, 30, 9, -3, 0]}


Mapping List Elements

We can use map() method to map all elements using the provided function:.

fun main() {
val theList = listOf(10, 12, 30, 31, 40, 9, -3, 0)
val resultList = theList.map{ it / 3 }

println(resultList)
}

When you run the above Kotlin program, it will generate the following output:

[3, 4, 10, 10, 13, 3, -1, 0]

Chunking List Elements

We can use chunked() method to create chunks of the given size from a list. Last
chunk may not have the elements equal to the number of chunk size based on the
total number of elements in the list.

fun main() {
val theList = listOf(10, 12, 30, 31, 40, 9, -3, 0)
val resultList = theList.chunked(3)

println(resultList)
}

When you run the above Kotlin program, it will generate the following output:

[[10, 12, 30], [31, 40, 9], [-3, 0]]

Windowing List Elements

We can use windowed() method to a list of element ranges by moving a sliding


window of a given size over a collection of elements.

fun main() {
val theList = listOf(10, 12, 30, 31, 40, 9, -3, 0)
val resultList = theList.windowed(3)

println(resultList)
}

When you run the above Kotlin program, it will generate the following output:

[[10, 12, 30], [12, 30, 31], [30, 31, 40], [31, 40, 9], [40, 9, -3], [9, -3, 0]]

By default, the sliding window moves one step further each time but we can change
that by passing a custom step value:

fun main() {
val theList = listOf(10, 12, 30, 31, 40, 9, -3, 0)
val resultList = theList.windowed(3, 3)

println(resultList)
}

When you run the above Kotlin program, it will generate the following output:

[[10, 12, 30], [31, 40, 9]]

Kotlin mutable List

We can create mutable list using mutableListOf(), later we can use add() to add more
elements in the same list, and we can use remove() method to remove the elements
from the list.

fun main() {
val theList = mutableListOf (10, 20, 30)

theList.add(40)
theList.add(50)
println(theList)

theList.remove(10)
theList.remove(30)
println(theList)
}

When you run the above Kotlin program, it will generate the following output:

[10, 20, 30, 40, 50]


[20, 40, 50]
fun main() {

val list1 = mutableListOf<String>()


println("List1: $list1")
// Add individual items using add()
println("Add noodles: ${list1.add("noodles")}")
println("List1: $list1")
println("Add ABC: ${list1.add("ABC")}")
println("List1: $list1")
// Add a list of items using addAll()
val moreItems = listOf("XYZ", "HELLO", "DCSA")
println("Add list: ${list1.addAll(moreItems)}")
println("List1: $list1")
// Remove an item using remove()
println("Remove XYZ: ${list1.remove("XYZ")}")
println("List1: $list1")
println("Remove item that doesn't exist: ${list1.remove("rice")}")
println("List1: $list1")
// Remove an item using removeAt() with an index
println("Remove first element: ${list1.removeAt(0)}")
println("List1: $list1")
// Clear out the list
list1.clear()
println("List1: $list1")
// Check if the list is empty
println("Empty? ${list1.isEmpty()}")
}
OUTPUT

List1: []

Add noodles: true

List1: [noodles]

Add ABC: true

List1: [noodles, ABC]

Add list: true

List1: [noodles, ABC, XYZ, HELLO, DCSA]

Remove XYZ: true

List1: [noodles, ABC, HELLO, DCSA]

Remove item that doesn't exist: false

List1: [noodles, ABC, HELLO, DCSA]

Remove first element: noodles

List1: [ABC, HELLO, DCSA]

List1: []

Empty? true

You might also like