How to Use the "Filter" And "Map" Functions on Collections In Kotlin?

10 minutes read

In Kotlin, the "filter" and "map" functions are useful for manipulating collections such as lists, arrays, or sequences.


The "filter" function allows you to selectively retain elements from a collection based on a given condition. It takes a predicate that determines whether an element should be included in the resulting collection. The filtered elements are returned as a new collection.


For example:

1
2
3
val numbers = listOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter { it % 2 == 0 }
// Result: [2, 4]


In this example, the "filter" function is used to keep only the even numbers from the list of "numbers". The condition inside the lambda expression checks if each element is divisible by 2.


The "map" function, on the other hand, transforms each element of a collection based on a given transformation rule. It applies the transformation to each element and returns a new collection with the transformed values.


For example:

1
2
3
val numbers = listOf(1, 2, 3, 4, 5)
val squaredNumbers = numbers.map { it * it }
// Result: [1, 4, 9, 16, 25]


In this case, the "map" function is used to square each element of the "numbers" list. The lambda expression specifies the transformation rule.


Both "filter" and "map" functions are useful for functional programming and provide a concise way to manipulate collections in Kotlin. They help in performing common operations on collections without the need for manual iteration.

Best Kotlin Books to Read in 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Kotlin in Action

Rating is 4.9 out of 5

Kotlin in Action

3
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.8 out of 5

Kotlin Cookbook: A Problem-Focused Approach

4
Head First Kotlin: A Brain-Friendly Guide

Rating is 4.7 out of 5

Head First Kotlin: A Brain-Friendly Guide

5
Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

Rating is 4.6 out of 5

Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

6
Effective Kotlin: Best Practices (Kotlin for Developers Book 5)

Rating is 4.5 out of 5

Effective Kotlin: Best Practices (Kotlin for Developers Book 5)

7
Java to Kotlin: A Refactoring Guidebook

Rating is 4.4 out of 5

Java to Kotlin: A Refactoring Guidebook

8
Learn to Program with Kotlin: From the Basics to Projects with Text and Image Processing

Rating is 4.3 out of 5

Learn to Program with Kotlin: From the Basics to Projects with Text and Image Processing


How to use the mapNotNull function on collections in Kotlin?

The mapNotNull function is used to transform a collection by applying a transformation function to each element and then filtering out the resulting null values.


Here's how you can use mapNotNull function on collections in Kotlin:

  1. Start by creating a collection (e.g., a list):
1
val numbers = listOf(1, 2, 3, 4, 5)


  1. Use the mapNotNull function to transform the collection, providing a lambda function as the transformation function that returns the transformed value (or null if necessary):
1
2
3
4
5
6
7
val transformedList = numbers.mapNotNull { number ->
    if (number % 2 == 0) {
        number * 2 // Return the transformed value
    } else {
        null // Filter out odd numbers by returning null
    }
}


In this example, the lambda function checks if an element is even (i.e., divisible by 2), and if so, it returns the element multiplied by 2. If an element is odd, it returns null.

  1. The resulting transformedList will only contain the non-null transformed elements:
1
println(transformedList) // Output: [4, 8]


In this case, only the even numbers were transformed and included in the result.


Note that mapNotNull function returns a new collection containing the transformed non-null elements, without modifying the original collection.


How to apply multiple map functions in Kotlin?

In Kotlin, you can apply multiple map functions by chaining them together using the map function. Here's an example:

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

val squaredEvenNumbers = numbers
    .filter { it % 2 == 0 }         // Filter even numbers
    .map { it * it }                // Square each number

println(squaredEvenNumbers)         // Output: [4, 16]


In this example, we start with a list of numbers and apply two map functions. First, we filter out the even numbers using the filter function, and then we square each number using the map function. The result is a list of squared even numbers.


You can chain as many map functions as you need to apply multiple transformations to your data.


How to use the filterNotNull function on collections in Kotlin?

In Kotlin, the filterNotNull function can be used to filter out all the null values from a collection. Here's how you can use it:

1
2
3
4
5
val list: List<String?> = listOf("hello", null, "world", null, "kotlin", null)

val filteredList: List<String> = list.filterNotNull()

println(filteredList) // [hello, world, kotlin]


In the code above, we have a list of nullable strings (String?) that contains some null values. We use the filterNotNull function to get a new list (filteredList) that contains only the non-null values from the original list.


Note that the resulting list filteredList has type List<String> because the filterNotNull function removes all null values, effectively converting the nullable type to a non-null type.


You can use the filterNotNull function directly on other types of collections, such as arrays and sets, in a similar way.


How to filter a list based on a given condition in Kotlin?

In Kotlin, you can use the filter() function to filter a list based on a given condition. Here's an example:

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

val evenNumbers = numbers.filter { it % 2 == 0 }
println(evenNumbers) // Prints [2, 4]


In this example, the filter() function takes a lambda expression as a parameter, which specifies the condition for filtering. The lambda expression { it % 2 == 0 } checks if an element is divisible by 2 (i.e., an even number), and returns true if the condition is met.


The filter() function returns a new list that contains only the elements that satisfy the given condition. In this case, it creates a list evenNumbers that contains only the even numbers from the original numbers list.


You can replace the condition { it % 2 == 0 } with any other condition that suits your filtering needs.


What is the difference between filter and filterNot functions in Kotlin?

The filter and filterNot functions in Kotlin are used to filter elements from a collection based on a specified condition. The key difference between them lies in the filtering logic:

  1. filter function: It retains the elements that satisfy the given condition. The filtered elements are returned as a new collection. The original collection is not modified. It returns a list of elements that match the specified predicate.
  2. filterNot function: It retains the elements that do not satisfy the given condition. The filtered elements are returned as a new collection. The original collection is not modified. It returns a list of elements that do not match the specified predicate.


In simpler terms, filter keeps the elements that match the condition, while filterNot keeps the elements that do not match the condition.

Twitter LinkedIn Telegram Whatsapp

Related Posts:

Working with the Kotlin Collections API allows you to efficiently manage and manipulate collections of data in your Kotlin code. Kotlin provides a rich set of built-in functions and operators that make it easy to perform common operations on lists, sets, and m...
In Kotlin, you can initialize a big immutable map using the mapOf() function or the to notation. Here&#39;s how you can achieve it:Using the mapOf() function: Initialize a big immutable map by using the mapOf() function, providing key-value pairs in the form o...
To add markers to a Google Map using Kotlin, follow these steps:First, make sure you have included the necessary dependencies in your project&#39;s build.gradle file. Add the following lines to the dependencies block: implementation &#39;com.google.android.gms...