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

Viewed 149276

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

6 Answers

I am just sharing that if you have custom list and check whether it is null or blank you can check in Kotlin in single line Just do it like that

  fun filterList(listCutom: List<Custom>?) {
    var fiterList = listCutom!!.filter { it.label != "" }
    //Here you can get the list which is not having any kind of lable blank
  }

You can check multiple conditions also

 fun filterList(listCutom: List<Custom>?) {
    var fiterList = listCutom!!.filter { it.label != "" && it.value != ""}
    //Here you can get the list which is not having any kind of lable or value blank
  }

Note : I am assuming that label & value are the variables of Custom Model class.

Filtering by predicate

    val numbers = listOf("one", "two", "three", "four")
    var items: List<String> = numbers.filter { s -> s == "one" }

    var item = numbers.singleOrNull { it == "one" }

    if (item != null) {
        print("FOUND:$item")
    } else {
        print("Not FOUND!")
    }
Related