1.移除相同的木个元素
1.使用过滤器
scanResults = scanResults.filter { it != ewmString }.toMutableList()
2.使用 removeAll
scanResults.removeAll { it == ewmString }
2.添加字符串拼接 , 号
常用 字符串 a+=b.a+“,”
scanResults += "$result,"
直接添加 result 值
scanResults += result
// 输出时拼接为带逗号的字符串
val resultString = scanResults.joinToString(",")
// 使用 joinToString 替代手动拼接
val caseNumber = lists.joinToString(",") { it.caseNumber }
3.三目运算
1.给实体木个属性赋值
// 设置 xwsApply 的 caseNumber 属性
xwsApply?.caseNumber = if (caseNumber.isNotEmpty()) {
ComData.subString(caseNumber)
} else {
""
}
2.给单独对象赋值
1.非空检查
如果 result 可能为 null,可以在赋值前进行非空检查
if (result != null) {
ewmString = result
} else {
ewmString = "" // 或者设置默认值
}
2.改进二:使用安全调用
Kotlin 提供了安全调用操作符 ?.,可以简化非空检查:
ewmString = result ?: ""
这里的 ?: 表示如果 result 为 null,则使用右侧的默认值(如空字符串 "")。
4.判断木个对象的值跟数组中的值一样添加到数组中
1.Stream 的使用
使用 stream().noneMatch 方法替代传统的 for 循环,使代码更加简洁。
noneMatch 方法会在找到匹配项时立即停止遍历,避免不必要的循环。
ApplyWuPin applyWuPin = (ApplyWuPin) params[0];
if (applyWuPin != null &&
listsWuPin.stream().noneMatch(item -> item.getCaseNumber().equals(applyWuPin.getCaseNumber()))) {
listsWuPin.add(applyWuPin);
}
2. Set(如 HashSet),以利用其快速查找特性
Set<String> caseNumberSet = listsWuPin.stream()
.map(ApplyWuPin::getCaseNumber)
.collect(Collectors.toSet());
ApplyWuPin applyWuPin = (ApplyWuPin) params[0];
if (applyWuPin != null && !caseNumberSet.contains(applyWuPin.getCaseNumber())) {
listsWuPin.add(applyWuPin);
caseNumberSet.add(applyWuPin.getCaseNumber());
}
5.判断数组中木个值相似 修改数组中状态
listsTask.parallelStream()
.filter(item -> item != null && "true".equals(item.getDeleteId()))
.forEach(item -> item.setChecked(true));
1.listsTask.parallelStream():
创建一个并行流(parallelStream),允许对 listsTask 列表中的元素进行并行处理。
并行流会利用多核 CPU 的优势,将任务拆分为多个子任务并在多个线程中同时执行。
2..filter(item -> item != null && "true".equals(item.getDeleteId())):
使用 filter 方法对列表中的每个元素进行过滤。
过滤条件是:元素不为 null,并且其 DeleteId 属性等于字符串 "true"。
注意这里使用 "true".equals(item.getDeleteId()) 而不是 item.getDeleteId().equals("true"),以避免 getDeleteId() 返回 null 时抛出 NullPointerException。
3..forEach(item -> item.setChecked(true)):
对过滤后的每个元素调用 setChecked(true) 方法,将其标记为选中状态。
forEach 是一种终端操作,表示对流中的每个元素执行指定的操作。
6.移除数组中 属性跟其他属性一样的对象
listsCheck.removeIf(item -> item.getId().equals(ratailInfo.getId()));
5.判断数组中某个值大于60
fun <T> Iterable<T>.any(predicate: (T) -> Boolean): Boolean
volumeList.any { it.toInt() > 60 } 的意思是:
遍历 volumeList 中的所有元素。
对每个元素,将其从字符串转换为整数,并判断是否大于 60。
如果有任何一个元素满足条件(即大于 60),则返回 true;否则返回 false
找到一个满足条件的元素,any 函数立即返回 true,不再继续遍历剩余元素。