Practice Time: List Filters

 Lets say, we have a list of decorations, to print all decorations that start with the letter P, we can filter the decorations and return a list of the list of elements that match the condition under filter.



/** File:           Main.kt
* Programmer: Nolverto Urias Obeso
* Creation Date: 06/13/2023
* Description: Use the filters in a list
*/

fun main() {
val decorations = listOf("rock","pagoda", "plastic plants","alligator","flowerpot")

// Filter 1: Return all elements if the condition is true
println(decorations.filter { true }) // Output: [rock, pagoda, plastic plants, alligator, flowerpot]

// Filter 2: Return only the elements that have the initial character p
println(decorations.filter { it[0] == 'p' }) // Output: [pagoda, plastic plants]

}
Output:
[rock, pagoda, plastic plants, alligator, flowerpot]
[pagoda, plastic plants]

Comments

Popular posts from this blog