How can I filter out an ArrayList in Kotlin so that I only have elements that match my state?

I have an array:

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

I have to filter the list so that I have only one "January".

+43
source share
5 answers

You can use this code to filter January from an array 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()
+65
source

There are many functions for filtering collections, if you want to save only the values ​​that correspond "January", you can use a simple one 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"

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

, "January", != filterNot()

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

, "February" "March".

, Java, == != Kotlin equals . . equality.

API.

+32

, .

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

filterNot() . , , .

var filteredMonthList : List<String> = month.filterNot { s -> s == "January" }
// results:  ["February", "March"]

filter(). , , .

var filteredMonthList : List<String> = month.filter { s -> s == "January" }
// results:  ["January"]

filter() single() , .

var filteredMonth : String = month.filter { s -> s == "January" }.single()
// result:  "January"
+11

, , , Kotlin .

  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
  }

.

 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
  }

. , .

+7

You can also use find or findLast. This is specifically designed to return only one value instead of the list Stringreturned in the case filter.

var month = arrayListOf("January", "February", "March")
var result = month.find { s -> s == "January" }
+4
source

Source: https://habr.com/ru/post/1677649/


All Articles