How to filter a list in Kotlin

Overview

A list is an ordered collection of elements. In this shot, we will learn how to filter a list in Kotlin.

The filter method in Kotlin filters the elements in the list with certain criteria. We pass lambda expressions to the filter with conditions.

Syntax

list.filter{
//condition
}

Example

In this example, we will filter out the odd numbers from a list of numbers.

fun main(){
//The given numbers
val nums = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
//Filtering the odd numbers
val oddNums = nums.filter{ it % 2 != 0 }
//Displaying the odd numbers
print(oddNums)
}

Explanation

  • Line 1: We define the main() function. It is mandatory to define this function because the program execution starts from it. We write our further code in this main function.
  • Line 4: We declare and initialize the list of numbers, nums.
  • Line 7: We filter the odd numbers using the filter method on the nums list. We store the returned numbers in the oddNums variable.
  • Line 10: We display the oddNums list.

Free Resources