Search code examples
listkotlinfiltering

How can I filter an ArrayList in Kotlin so I only have elements which match my condition?


I have an array:

var month: List<String> = arrayListOf("January", "February", "March")

I have to filter the list so I am left with only "January".


Solution

  • You can use this code to filter out January from array, by using this code

    var month: List<String> = arrayListOf("January", "February", "March")
    // to get the result as list
    var monthList: List<String> = month.filter { s -> s == "January" }
    
    // to get a string
    var selectedMonth: String = month.filter { s -> s == "January" }.single()