如何在Kotlin中检查字符串数组是否包含某个值?就像Ruby的
我考虑了以下方法:
有其他的方法吗?
#include?
一样。我考虑了以下方法:
array.filter { it == "value" }.any()
有其他的方法吗?
您还可以使用any()
来检查数组中是否存在具有特定字段与之进行比较的对象。
listOfObjects.any{ object -> object.fieldxyz == value_to_compare_here }
以下是一段代码,可用于在包含对象的ArrayList中查找特定字段。Amar Jain的回答对我很有帮助:
listOfObjects.any{ it.field == "value"}
使用 in 操作符是一种惯用的方法来做到这一点。
val contains = "a" in arrayOf("a", "b", "c")
你可以使用它..contains(" ")
data class Animal (val name:String)
val animals = listOf(Animal("Lion"), Animal("Elephant"), Animal("Tiger"))
println(animals.filter { it.name.contains("n") }.toString())
输出将会是
[Animal(name=Lion), Animal(name=Elephant)]
find
方法,返回与给定的[predicate]匹配的第一个元素,如果没有找到这样的元素,则返回null
。
尝试使用以下代码在对象array
中查找value
。 val findedElement = array?.find {
it.id == value.id
}
if (findedElement != null) {
//your code here
}
array.indexIf(Object o)
来查找元素的位置,它会返回第一个匹配元素的索引;使用array.lastIndexOf(Object o)
则会返回最后一个匹配元素的索引。你也可以使用谓词,例如array.indexOfLast { it.name == "test " }
或者array.indexOfFirst { it.name == "test "}
等。 - L.Petrosyan