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


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

There are a number of functions for filtering collections, if you want to keep only values matching "January", you can use the simple filter():

val months = listOf("January", "February", "March")

months.filter { month -> month == "January" } // with explicit parameter name
months.filter { it == "January" }             // with implicit parameter name "it"

These will give you a list containing only "January".

If you want all months that are not "January", you can either reverse the condition using !=, or use filterNot():

months.filter { it != "January" }
months.filterNot { it == "January" } 

These will give you a list containing "February" and "March".

Note that unlike Java, using the == and != operators in Kotlin is actually the same as calling the equals function on the objects. For more, see the docs about equality.

For the complete list of collection functions in the standard library, see the API reference.