list 如何在 Kotlin 中过滤 ArrayList 以便我只有符合我的条件的元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44098709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 08:13:39  来源:igfitidea点击:

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

listkotlinfiltering

提问by Nitt

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

我必须过滤列表,所以我只剩下"January".

回答by Nithinlal

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

回答by zsmb13

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

有许多过滤集合的函数,如果你只想保持匹配的值"January",你可以使用简单的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".

这些将为您提供一个仅包含"January".

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

如果您想要所有不是 的月份"January",您可以使用!=或使用来反转条件filterNot()

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

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

这些将为您提供一个包含"February"和的列表"March"

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

请注意,与 Java 不同的是==!=在 Kotlin 中使用and运算符实际上与equals在对象上调用函数相同。如需更多信息,请参阅有关文档平等

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

有关标准库中集合函数的完整列表,请参阅API 参考

回答by Avijit Karmakar

You want to filter this list of Strings containing months.

您想过滤此包含月份的字符串列表。

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

You can use filterNot()method of list. It returns a list containing all elements except the given predicate.

您可以使用filterNot()列表的方法。它返回一个包含除给定谓词之外的所有元素的列表。

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

You can use filter()method of list. It returns a list containing all elements matching the given predicate.

您可以使用filter()列表的方法。它返回一个包含与给定谓词匹配的所有元素的列表。

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

After filter()if we use single()method then it will return a single value and throw an exception if more than one value is in the list.

之后,filter()如果我们使用single()方法,那么它将返回单个值并在列表中包含多个值时抛出异常。

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

回答by Mohit Suthar

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

我只是分享一下,如果您有自定义列表并检查它是否为空或空白,您可以单行检查 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
  }

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 & valueare the variables of CustomModel class.

注意:我假设标签和值自定义模型类的变量。

回答by Rishabh876

You can also use findor findLast. This is specifically meant to return only one value instead of a list of Stringreturned in case of filter.

您也可以使用findfindLast。这特别意味着仅返回一个值,而不是Stringfilter.

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

回答by Shomu

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!")
    }