0

I am trying to remove Elements of a list if they have been included in a text file.

For example: If the String "Person123" was in the text file then the String "Person123" should be removed from the list.

Below is my current attempt. However I am getting an issue with iterating through "MyList", the int value does not seem to increment which is causing only one of the string elements to be removed, rather than two.

How can I fix this?

Current Code:

for (Map.Entry<Person, List<String>> entry : mapOfPeopleAndDescriptions.entrySet()) {
    List<String> textFileValues= readFromTextFile(filePath);
    List<String> myList = entry.getValue();

    for (int i = 0; i < myList.size(); i++) {

                if(textFileValues.contains(myList.get(i)){

                    LOGGER.info("In loop- int: {}",i );
                    myList.remove(myList.get(i));

                }

                LOGGER.info("Out of loop- int: {}",i );

            }

    }

Output I am getting:

In loop- int: 0
Out of loop- int: 0
Out of loop- int: 1
Out of loop- int: 0
Out of loop- int: 1
Out of loop- int: 0
java123999
  • 6,974
  • 36
  • 77
  • 121

2 Answers2

2

The for loop is unnecessary. Simply use List.removeAll:

myList.removeAll(textFileValues);

Note that if you are iterating by index and removing elements, you should do it in reverse:

for (int i = myList.size(); i >= 0; i--) {
  myList.remove(i);
}

Otherwise, you will need to change the value of i in the loop to avoid skipping the next element.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

You should use an iterator and then call the remove method : Iterator.remove().

See this thread.

Community
  • 1
  • 1
Akah
  • 1,890
  • 20
  • 28