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

Nitt picture Nitt · May 21, 2017 · Viewed 85k times · Source

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".

Answer

Nithinlal picture Nithinlal · May 21, 2017

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()