Kotlin .filter()
Published Oct 28, 2023
Contribute to Docs
The filter() function is used to filter elements from a collection based on a given predicate. It returns a new collection containing only elements that meet the given condition.
Syntax
str.filter(predicate)
The filter() method only allows the selective characters based on the specified predicate which is passed as an argument.
- The
predicateis a lambda function that takes an element of the collection as an argument and returns aBooleanvalue. Thefilter()method will return a collection composed of all the elements that evaluated totrue.
Example
This example extracts all the alphabetic characters from str with the string.filter() method.
fun main(args: Array<String>) {val str = "Hello, World!"val result = str.filter({ it -> it.isLetter() })println("Filtered String : " + result)}
The above code will output:
Filtered String : HelloWorld
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Kotlin on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn Kotlin, the expressive, open-source programming language developed by JetBrains.
- Beginner Friendly.9 hours