Kotlin

10 Kotlin list Tips & Tricks

Google+ Pinterest LinkedIn Tumblr

Lists in Kotlin are very useful. It is the most used data structure and it can be used in a multitude of different ways to model and solve a whole bunch of problems. Lists are SO awesome. In this article, we’ll look at some of the tips and tricks when working with Kotlin lists.

Most of these “tricks” I mostly used in my day-to-day development and I hope you’ll find them useful too.

Show me the code:

Find the most frequent value

import java.util.*

val list = listOf("Ahsen","Saeed","Just","Another","Programming Nerd","Ahsen")

fun main() {
    val countByElement = list.groupingBy { it }.eachCount()
    val maximumElement = countByElement.maxBy { it.value }?.key
    println(maximumElement) 
}

// Output of above program
Ahsen

Create a single string from all the elements in the List

import java.util.*

val list = listOf("Ahsen","Saeed","Just","Another","Programming")

fun main() {
   val joinedString = list.joinToString(prefix = "Hey There, ", separator = " ", postfix = " Nerd")
   println(joinedString)
}

// Output
Hey There, Ahsen Saeed Just Another Programming Nerd

The above joinToString creates a string from all the elements separated using separator and using the given the prefix and postfix. Here are the default values for the above joinToString method.

Parameter NameDefault Value
separator“,”
prefix“”
postfix“”

Swapping two lists

import java.util.*

fun main() {
    var (first,second) = listOf(1,2,3,4,5) to listOf(6,7,8,9,10)
    println("Before swapping: first -> $first and second -> $second")
    first = second.also { second = first }
    println("After swapping: first -> $first and second -> $second")
}

// Output
Before swapping: first -> [1, 2, 3, 4, 5] and second -> [6, 7, 8, 9, 10]
After swapping: first -> [6, 7, 8, 9, 10] and second -> [1, 2, 3, 4, 5]

Sort list in ascending or descending order

import java.util.*

val avengerNames = listOf("Chris Evans", "Jeremy Renner", "Scarlett johansson", "Josh Brolin", "Chris Hemsworth")
val numbers = listOf(5, 8, 1, 6, 10, 4, 7, 3, 9, 2)

fun main() {
   val avengersNamesAscendingOrder = avengerNames.sorted()
   val avengersNamesDescendingOrder = avengerNames.sortedDescending()
   val numbersInAscending = numbers.sorted()
   val numbersInDescending = numbers.sortedDescending()
   println("Avengers names in ascending -> $avengersNamesAscendingOrder")
   println("Avengers names in descending $avengersNamesDescendingOrder")
   println("Numbers in ascending -> $numbersInAscending")
   println("Numbers in descending -> $numbersInDescending")
}

// Output of above program
Avengers names in ascending -> [Chris Evans, Chris Hemsworth, Jeremy Renner, Josh Brolin, Scarlett johansson]
Avengers names in descending [Scarlett johansson, Josh Brolin, Jeremy Renner, Chris Hemsworth, Chris Evans]
Numbers in ascending -> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Numbers in descending -> [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Remove duplicate from list

import java.util.*

val numbers = listOf(1, 2, 3, 4, 5, 1, 2, 3, 6, 7, 5, 9, 10)

fun main() {
   val distinctedList = numbers.distinct()
   println(distinctedList)
}

// Output
[1, 2, 3, 4, 5, 6, 7, 9, 10]

The distinct method works well with other data types.

Find min and max elements

import java.util.*

val animals = listOf("Baboon", "Argalis", "Cat", "Lion", "Monkey", "Zebra", "Fox", "Elephant")
val numbers = listOf(10, 2, 3, 4, 5, 1, 2, 3, 6, 7, 5, 9)

fun main() {
   val minAnimal = animals.min()
   val maxAnimal = animals.max()
   val minNumber = numbers.min()
   val maxNumber = numbers.max()
   println("Min animal: $minAnimal, max animal: $maxAnimal, min number: $minNumber, and max number: $maxNumber")
}

// Output
Min animal: Argalis, max animal: Zebra, min number: 1, and max number: 10

Perform some computation on the list and return Result

import java.util.*

val numbers = listOf(1, 2, 3, 4, 5)

fun main() {
   val productResult = numbers.reduce { x, y -> x * y}
   println(productResult)
} 

// Output
120

The reduce method is a little complicated so I try to explain it’s inner working. Initially, the reduce method calls out the first two items from a list and returned the result. The function is then called again with the result obtained previously and the next value in the list. This process keeps repeating until there are items on the list.

You can check out this question on Stack Overflow: Difference between reduce and fold method

Reverse a list

import java.util.*

val avengers = listOf("Chris Evans", "Jeremy Renner", "Scarlett johansson", "Josh Brolin", "Chris Hemsworth")

fun main() {
   val reversedAvengers = avengers.reversed()
   println(reversedAvengers)
}

// Output
[Chris Hemsworth, Josh Brolin, Scarlett johansson, Jeremy Renner, Chris Evans]

Perform a binary search

import java.util.*

val animals = listOf("Baboon", "Argalis", "Cat", "Lion", "Monkey", "Zebra", "Fox", "Elephant")

fun main() {
   val sortedAnimals = animals.sorted()
   val index = sortedAnimals.binarySearch("Lion")
   println(sortedAnimals[index]) 
}

// Output
Lion

Note from binarySearch method documentation: The list is expected to be sorted into ascending order according to the Comparable natural ordering of its elements, otherwise, the result will be undefined.

Fast way to convert an array into List

data class Person(val name: String, val age: Int)

val array = arrayOf<Person>()
val list = array.toList()

If you think I should add more or have any suggestion please do comment below. I’ll keep updating this article. Also, if you like the article don’t forget to hit the ♥️ button below.

Thank you for being here and keep reading…

3 Comments

    • ahsensaeed067 Reply

      Yes, I know the filter function is a must but the thing is everyone knows how the filter works that’s why I try not to include this method in the above mention list.

Write A Comment