There is a question about processing the list elements with forEach loop.
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);
});
}
});
After removing B, C from stringsToRemove array also , the values are processed as per original list elements.
How to modify the outer loop to only consider the remaining elements to process? Any help will be appreciated.
At the same time , the traditional for loop works well.
for(int i = 0; i < stringsToRemove .size(); i++)
{
stringsToRemove.removeAll(deleteDeviceAndReferences());
}
Complete code:
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;
}
}