如何在 Java 中的 for 循环中模拟字符串列表的'except'?



我有一个字符串列表(partList),它是另一个字符串(completeList)列表的一部分,我想在for循环中处理一个对象(通过processObj()),使partList的当前元素从completeList中收回:当当前迭代在partList的元素上时,对象的处理将涉及该元素和完整列表中的其余元素我现在喜欢这样做:

for (String el: partList) {
completeList.remove(el);
//process the target object using as parameters el and the rest of the complete list except el...
processObj(el,completeList);
completeList.add(el);
}

这是正确的做法吗?谢谢你的启示。

我不确定删除然后添加回同一列表的目的,但您可以使用Predicate来接受和处理某些值。

Predicate<String> accept = (s) -> {
return true;  // accepts all strings; you could use partList.contains(s) here, or !s.equals(el)
}
completeList.stream()
.filter(accept.negate()) // Inverse the predicate to implement "except" 
.forEach(processObj); 

如果要修改流值,请将forEach替换为map,然后可以使用collect()将数据返回到列表中。

最新更新