0

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;

    }
}

1 Answer 1

1

Your loop doesn't actually seem to make use of the individual device you're iterating on. Your code looks like it should be equivalent to not looping at all, just calling

stringsToRemove.removeAll(deleteDeviceAndReferences());

without any loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.