有群友贴了如下代码问怎么更优雅一点呢?
private fun addMiddlePannel(temp: MutableList<SelectBean>): Boolean {
var select: SelectBean?
var isHasMiddle = false
for (i in 0 until temp.size) {
println("$i ${temp[i]}")
select = temp[i]
if (2 == select.dirition) {
temp.remove(select)
isHasMiddle = true
break
}
}
return isHasMiddle
}
当然呢这个代码是有点问题的,需求是要全部移除而且要知道是否移除了,那就需要修改temp的同时返回一个Boolean值,知道需求了就开干。 这里使用removeIf来实现。

/**
* removeIf 方法使用
* https://developer.android.google.cn/reference/java/util/Collection?hl=en#removeIf(java.util.function.Predicate%3C?%20super%20E%3E)
*/
private fun addMiddlePannel(temp: MutableList<SelectBean>): Boolean {
var isHasMiddle = false
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
isHasMiddle = temp.removeIf { it.dirition == 3 }
} else {
val tempIterator = temp.iterator()
while (tempIterator.hasNext()) {
val select = tempIterator.next()
if (select.dirition == 3) {
tempIterator.remove()
isHasMiddle = true
}
}
}
return isHasMiddle
}
有什么更好的写法欢迎来一起探讨一下,我在评论区等你。
