.filter()
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
predicate
is a lambda function that takes an element of the collection as an argument and returns aBoolean
value. 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
Looking to contribute?
- 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.