Kotlin Array - dropWhile() Function



The Kotlin array dropWhile() function is used to retrieve the list contains the all elements except the first n elements that satisfy the given predicate, or condition.

This function takes a less than (<) operator and deletes all the element from the first to given condition. For example; dropWhile{it < 'x'} removes all elements preceding the x

Syntax

Following is the syntax of Kotlin array dropWhile() function −

fun <T> Array<out T>.dropWhile(
    predicate: (T) -> Boolean
): List<T>

Parameters

This function accepts a predicate function as a parameter. This predicate function represent the number of elements from the beginning index of an array that need to be dropped.

Return value

This function returns a list containing all elements left after being dropped.

Example 1

Following is the basic example to demonstrate the use of dropWhile() function −

fun main(args: Array<String>) {
   val number: Array<Int> = arrayOf(1, 2, 3, 4, 5, 6, 7, 8)
   val after_dropWhile = number.dropWhile{it<5}
   println("list after dropped: $after_dropWhile")
}

Output

On execution of the above code we get the following result −

list after dropped: [5, 6, 7, 8]

Example 2

Now, let's see another example. We create an array that stores strings. We then use the dropWhile() function to drop the first n elements while we get "tutorix" −

fun main(args: Array<String>) {
   val strings: Array<String> = arrayOf("hii", "Hello", "tutorix", "tutorialspoint")
   val after_dropWhile = strings.dropWhile{it<"tutorix"}
   println("list after dropped: $after_dropWhile")
}

Output

After execution of the above code we get the following output −

list after dropWhileped: [tutorix, tutorialspoint]

Example 3

The example below creates an array of 26 characters. We then use dropWhile() to drop the first n element while we get the 'm' −

fun main(args: Array<String>) {
   // Create an array of characters from 'a' to 'z'
   val alphabet: Array<Char> = ('a'..'z').toList().toTypedArray()
   
   // Drop the first n elements from the array
   val after_Drop = alphabet.dropWhile{it<'m'}
   
   println("List after dropping the first n elements: $after_Drop")
}

Output

The above code produce following output −

List after dropping the first n elements: [m, n, o, p, q, r, s, t, u, v, w, x, y, z]
kotlin_arrays.htm
Advertisements