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

Create a single string from all the elements in the List

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

Sort list in ascending or descending order

Remove duplicate from list

The distinct method works well with other data types.

Find min and max elements

Perform some computation on the list and return Result

The reduce method is 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 in 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

Perform a binary search

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

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…

Author

2 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