Kotlin has several standard functions for arrays and collections such as lists, sets or maps that make working with these data structures easier and more efficient. Some of these features are presented below, along with code examples and common use cases.
isEmpty() and isNotEmpty()
The isEmpty ()function exists true return if an array or collection such as List, Set or Map is empty, i.e. contains no elements; otherwise it gives false .
isNotEmpty(): This function returns true return if an array or collection contains at least one element; otherwise it gives false .
Application example: When working with arrays or collections you can isEmpty () or isNotEmpty() Use to check whether the data structure contains elements or not before accessing or performing operations on it.
count ()
The function returns the number of elements in an array or collection (list or set). An example of the use of count () You can also use the following:
The count ()function can also be used with a predicative lambda expression to count the number of elements that satisfy a specific condition. The example below finds the number of even numbers in an array:
In this case, the lambda expression checks whether the element (represented by it) 2 module equal 0 is, meaning it is an even number. The count ()function returns the number of elements that satisfy the condition in the lambda expression.
Application example: The count ()function is used in many situations where you want to apply a condition to all elements in a collection and determine the number of elements that meet that condition. For example, it can be used to count string elements that have a specific length or contain a specific pattern.
contains()
The contains()function in Kotlin is a convenient way to check whether an array or collection (List or Set) contains a specific element. She gives true return if the element exists in the collection, otherwise false.
Use case: A common use case for the contains()function in Kotlin is to check whether a specific item is contained in a collection before performing a specific action (For example, checking whether a username exists in databases).
first() and last()
The first()- and load()Functions in Kotlin are useful for getting the first and last element of a collection. They can also be used with a condition to get the first or last element that meets the specified condition. Here are some examples and use cases:
Get the first and last element that satisfies a condition:
Application example: Find start or end points in a collection of visitor times (an array of timestamps) to determine the time of the first and last visit.
maxOrNull() and minOrNull()
Features maxOrNull() and minOrNull() return the largest or smallest element of an array or collection or nullif the array is empty.
Application example: Determining a price range for a product category in an online shop.
average()
The average()function in Kotlin is useful to calculate the average value of an array or collection of numeric values. This function is for collections with elements of type Byte, Shorts, Int, Long, Float and Double available. Below is an example:
Application example: Common use cases for the average()function in Kotlin is to calculate the average of numerical data, such as: B. determining average prices, average scores or average temperatures.
sorted(), sortedDescending(), sortedBy(), sortedByDescending()
Kotlin has several functions for sorting arrays and collections in ascending or descending order or based on user-defined criteria. Here are the features and some use cases:
sorted()
The sorted()function sorts an array or collection of numbers or strings in ascending order.
sortedDescending()
The sortedDescending()function sorts an array or collection of numbers or strings in descending order.
sortedBy()
This function sorts an array or collection of objects in ascending order based on a user-defined property.
In this example is arrayOfWords a list of strings. The sortedBy()function is used to sort the list based on the length of the strings. The lambda function { it.length } returns the length of each element in the list, and sortedBy() uses this length to sort the elements in ascending order.
sortedByDescending()
This function sorts an array or collection in descending order based on a user-defined property. Below is an example that sorts an array of numbers in descending order based on the remainder of their division by 3:
Application examples: The sorted(), sortedDescending(), sortedBy() and sortedByDescending() Functions are useful for sorting collections based on various criteria. They can be used in many use cases such as: For example, to create rankings, prepare data for reports or presentations, or to optimize user interactions in an application.
distinct()
The distinct()function in Kotlin is used to remove duplicates from an array or collection and return a new collection with only unique elements.
Removed in this example distinct() the duplicates from the array arrayOfNumbers and returns a new list distinctNumbers with the unique numbers.
An example of removing duplicate strings from an array:
indexOf() and lastIndexOf()
The indexOf ()- and lastIndexOf ()Functions in Kotlin are used to find the index of a specific element in an array or collection.
indexOf ()
The indexOf ()function returns the first index at which the searched element is found. If the element does not exist, the function returns -1 .
In this example there is the indexOf ()-Function returns the first index at which the word yellow in the array arrayWithColors Is found.
lastIndexOf ()
The lastIndexOf ()function in Kotlin is used to find the last index of a particular element in an array or collection, such as a list or array. This function searches the collection backward, starting at the end of the collection, and returns the index of the last occurrence of the searched element. If the element does not exist in the collection, the function returns -1 .
Application example: Finding the frequency of an item in a collection by indexOf () and lastIndexOf () can be used to find the first and last index of the element and then traverse the range between these indexes.
forEach()
The forEach()function in Kotlin is a higher-order function that allows iterating over the elements of an array or collection and performing a specific action on each element.
In this case the forEach() function used to get over the elements of the array arrayOfNumbers to iterate. For each element in the array, the lambda expression is placed inside the curly braces {} executed.
Alternatively, you can also use the implicit one it-Use variable. An implicit name is a predefined, automatically assigned name for a variable or object without the programmer having to specify it explicitly. In Kotlin the implicit variable it used to reference the current element in a lambda expression when no explicit name is provided.
Application example: Sending personalized emails to a list of users.
folder ()
In Kotlin is folder () a function that can be applied to arrays or collections such as lists or sets. It is used to create a new collection by modifying each element of the original collection using a given transformation function. The transform function is provided as a lambda expression.
Application example: A common use case for the folder ()function is the conversion of elements of a collection into another form or data type. For example, one could convert a list of prices in one currency into a list of prices in another currency.
filter()
The filter()function in Kotlin is an extension function that can be applied to collections such as lists, sets or arrays. It allows you to create a new collection that contains only the items that meet a specific condition. The condition is provided as a lambda expression.
Application example: Filter students who have achieved a certain minimum grade point average.