查找是否在列表中找到具有特定 属性 值的元素
Find if an element with a specific property value is found in a list
我试图在 kotlin 中的对象列表中找到一个值,使用它 "filter",但如果找到该值,我需要 return true 或 false,但过滤return如果匹配,请给我一个对象列表。
t.filter { it.retailerId == value }
¿当我在对象列表中找到这个值时,如何才能 return 一个布尔值?
您可以将 firstOrNull()
与特定谓词一起使用:
val found = t.firstOrNull { it.retailerId == value } != null
如果firstOrNull()
没有return null
这意味着找到了值。
如果您需要元素正好是一个:
t.filter { it.retailerId == value }.size == 1
如果没有:
t.any { it.retailerId == value }
使用 foldRight 并在找到它时中断:
t.foldRight(false) {val, res ->
if(it.retailerId == value) {
return@foldRight true
} else {
res
}
}
除了firstOrNull
,您还可以使用具有相同谓词的any
:
val found = t.any { it.retailerId == value }
Kotlin 有这个很好的扩展功能,你可以使用
if (none { it.isSelected == true }) {
first().isSelected = true
}
对于单个元素
list.first { it.type == 2 (eg: conditions) }
or
list.firstOrNull { it.type == 2 (eg: conditions) }
对于元素列表
list.filter { it.type == 2 (eg: conditions) }
我试图在 kotlin 中的对象列表中找到一个值,使用它 "filter",但如果找到该值,我需要 return true 或 false,但过滤return如果匹配,请给我一个对象列表。
t.filter { it.retailerId == value }
¿当我在对象列表中找到这个值时,如何才能 return 一个布尔值?
您可以将 firstOrNull()
与特定谓词一起使用:
val found = t.firstOrNull { it.retailerId == value } != null
如果firstOrNull()
没有return null
这意味着找到了值。
如果您需要元素正好是一个:
t.filter { it.retailerId == value }.size == 1
如果没有:
t.any { it.retailerId == value }
使用 foldRight 并在找到它时中断:
t.foldRight(false) {val, res ->
if(it.retailerId == value) {
return@foldRight true
} else {
res
}
}
除了firstOrNull
,您还可以使用具有相同谓词的any
:
val found = t.any { it.retailerId == value }
Kotlin 有这个很好的扩展功能,你可以使用
if (none { it.isSelected == true }) {
first().isSelected = true
}
对于单个元素
list.first { it.type == 2 (eg: conditions) }
or
list.firstOrNull { it.type == 2 (eg: conditions) }
对于元素列表
list.filter { it.type == 2 (eg: conditions) }