Kotlin Array - takeWhile() Function



The Kotlin array takeWhile() function is used to return a list containing first element of an array satisfying the specified predicate.

Here, the first elements represent the result of applying the predicate to each element from the first of an array and stored in a new list.

Syntax

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

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

Parameters

This function accepts predicate as a parameter.

Return value

This function returns a list containing first n element that satisfies the predicate.

Example 1

Following is a basic example to demonstrate the use of takeWhile() function to return a list containing first elements less than specified predicate −

fun main(args: Array<String>){
   var arr = arrayOf(3, 4, 5, 6)
   print("Array elements: ")
   println(arr.joinToString())

   // use takeWhile function
   val list = arr.takeWhile({it<4})
   println("list: "+ list)
}

Output

The above code generate following output −

Array elements: 1, 2, 3, 4, 5
List: [1, 2, 3]

Example 2

Let's see another example. Here, we use the takeWhile function to return a list containing first elements having length less than 5 −

fun main(args: Array<String>){
   var arr = arrayOf<String>("Lily", "Rose", "Daisy", "Lotus", "Sunflower")
   print("Array elements: ")
   println(arr.joinToString())

   // use takeWhile function
   val list = arr.takeWhile({it.length<5})
   println("first n flower having length less than 5: ")
   println("list:" + list)
}

Output

Following is the output −

Array elements: Lily, Rose, Daisy, Lotus, Sunflower
first n flower having length less than 5: 
list:[Lily, Rose]

Example 3

Let's see below example where we have an array of Product objects, and we want to display first n elements having product price more than 100 using takeWhile() function −

data class Product(val name: String, val price: Double)
fun main(args: Array<String>) {
   val products = arrayOf(
      Product("Laptop", 999.99),
      Product("Mouse", 19.99),
      Product("Keyboard", 49.99),
      Product("Monitor", 199.99)
   )
   // use takeLast function
   val list = products.takeWhile{it.price>100}

   // Display the result
   println("Product and Price List: $list")
}

Output

The above code produce following output −

Product and Price List: [Product(name=Laptop, price=999.99)]
kotlin_arrays.htm
Advertisements