【发布时间】:2016-08-20 03:57:28
【问题描述】:
如果列表中的元素已包含在文本文件中,我正在尝试删除。
例如:如果字符串 "Person123" 在文本文件中,则应从列表中删除字符串 "Person123"。
以下是我目前的尝试。但是,我在迭代“MyList”时遇到问题,int 值似乎没有增加,这导致仅删除一个字符串元素,而不是两个。
我该如何解决这个问题?
当前代码:
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 );
}
}
我得到的输出:
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
【问题讨论】:
-
向后迭代列表。另外,请使用
myList.remove(i)。或使用Iterator。 -
@AndyTurner 你是什么意思?
-
for (int i = myList.size(); i >= 0; i--) { -
这是一个错字,现在改了,谢谢
-
myList.removeAll(textFileValues)会比这个循环容易得多。
标签: java list for-loop dictionary int