Kotlin String filterNotTo() Tutorial
The String.filterNotTo()
function in Kotlin is used to filter characters from a string based on a given predicate and add the results to a destination collection. It filters out the characters based on the specified condition and appends the results to the provided destination collection.
In this tutorial, we’ll explore the syntax of the filterNotTo()
function and provide examples of its usage in Kotlin strings.
Syntax
The syntax of the filterNotTo()
function is as follows:
fun String.filterNotTo(
destination: C,
predicate: (Char) -> Boolean
): C
where
Parameter | Description |
---|---|
destination | The destination collection to which the filtered characters are added. |
predicate | A function that defines the condition for filtering characters. It takes a character as an argument and returns true for characters to be excluded and false for characters to be included. |
The predicate
parameter is a function that determines whether a character should be excluded from the resulting collection. The function returns true
for characters that meet the specified condition and false
for those that do not. The filtered characters are then added to the specified destination collection.
Examples for String filterNotTo() function
1. Filter Out Vowels to a Destination
In this example, we’ll use filterNotTo()
to filter out vowels from a string and add the non-vowel characters to a destination variable.
- Take a string value in
originalString
. - Create an empty StringBuilder as the destination, e.g.,
nonVowelString
. - Define a predicate function that returns
true
for vowels andfalse
for non-vowel characters. - Call
filterNotTo()
function onoriginalString
with the destination and predicate function as arguments. The function adds non-vowel characters to the destination. - You may print the value in resulting destination variable
nonVowelString
to the console output.
Kotlin Program
fun main() {
val originalString = "Hello World"
// Create an empty StringBuilder as the destination collection
val nonVowelString = StringBuilder()
// Defining a predicate to filter out vowels
val predicate: (Char) -> Boolean = { it in "aeiouAEIOU" }
// Using filterNotTo() to exclude vowels from the original string and add non-vowel characters to the destination
originalString.filterNotTo(nonVowelString, predicate)
// Printing the original string and the resulting destination
println("Original String:\n$originalString\n")
println("Non-Vowel Characters :\n$nonVowelString")
}
Output
Original String:
Hello World
Non-Vowel String :
Hll Wrld
Summary
In this tutorial, we’ve covered the filterNotTo()
function in Kotlin strings, its syntax, and how to use it to filter characters based on a specified condition and add the results to a destination collection. This function provides a convenient way to selectively collect characters that do not meet the filtering criteria during the filtering process.