Practice Time: List Filters
Practice Time
You can do the following filter exercise in REPL.
- Create a list of spices, as follows:
val spices = listOf("curry", "pepper", "cayenne", "ginger", "red curry", "green curry", "red pepper" )
- Create a filter that gets all the curries and sorts them by string length.
- Hint: After you type the dot (.), IntelliJ will give you a list of functions you can apply.
- Filter the list of spices to return all the spices that start with 'c' and end in 'e'. Do it in two different ways.
- Take the first three elements of the list and return the ones that start with 'c'.
/** File: Main.kt
* Programmer: Nolverto Urias Obeso
* Creation Date: 06/13/2023
* Description: Use the filters in a list
*/
fun main() {
// 1. Create a list of spices
val spices = listOf("curry", "pepper", "cayenne", "ginger", "red curry", "green curry", "red pepper" )
// 2. Create a filter that gets all the curries and sorts them by string length
println(spices.filter { it.contains("curry")}.sortedBy { it.length })
// 3. Filter the list of spices to return all the spices that start with 'c' and end in 'e'.
// Do it in three different ways.
println(spices.filter { it[0] == 'c' && it[it.length-1]=='e' })
println(spices.filter { it.startsWith('c')}.filter { it.endsWith('e')})
println(spices.filter { it.startsWith('c') && it.endsWith('e')})
// 4. Take the first three elements of the list and return the ones that start with 'c'.
println(spices.take(3).filter { it.startsWith('c')})
}
Output:
[curry, red curry, green curry]
[cayenne]
[cayenne]
[cayenne]
[curry, cayenne]
Comments
Post a Comment