关于用forEach循环处理列表元素有一个问题。
List<String> stringsToRemove = {"A","B","C","D"};
stringsToRemove.forEach(device -> {
//calls the method (deleteDeviceAndReferences) which returns list of elements to //be removed from stringsToRemove. For Example C, B are returned from the method , the outer for //loop should not process those elements.
deleteDeviceAndReferences().forEach(removedevice -> {
stringsToRemove.remove(removedevice);
});
}
});
也从stringsToRemove数组中删除B、C后,值按原始列表元素处理。
如何修改外循环,使其只考虑要处理的剩余元素?如有任何帮助,不胜感激。
同时,传统的for循环也能很好地工作。
for(int i = 0; i < stringsToRemove .size(); i++)
{
stringsToRemove.removeAll(deleteDeviceAndReferences());
}
完整代码:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Test");
List<String> stringsToRemove = new CopyOnWriteArrayList<>();
stringsToRemove.add("A");
stringsToRemove.add("B");
stringsToRemove.add("C");
stringsToRemove.add("D");
stringsToRemove.forEach(device -> {
//calls the method (deleteDeviceAndReferences) which returns list of elements to //be removed from stringsToRemove. For Example C, B are returned from the method , the outer for //loop should not process those elements.
deleteDeviceAndReferences().forEach(removedevice -> {
stringsToRemove.remove(removedevice);
});
//stringsToRemove.removeAll(deleteDeviceAndReferences());
System.out.println("Processing"+stringsToRemove);
});
for(int i = 0; i < stringsToRemove .size(); i++)
{
stringsToRemove.removeAll(deleteDeviceAndReferences());
System.out.println("Processing"+stringsToRemove);
}
}
private static List<String> deleteDeviceAndReferences() {
List<String> elementsToValidate = new ArrayList<>();
elementsToValidate.add("B");
elementsToValidate.add("C");
return elementsToValidate;
}
}
你的循环实际上似乎没有利用你正在迭代的单个设备。你的代码看起来应该等同于根本不循环,只调用
stringsToRemove.removeAll(deleteDeviceAndReferences());
没有任何循环。